home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / tex / webtp55.zip / TANGLE.WEB (.txt) < prev    next >
Texinfo Document  |  1989-11-02  |  133KB  |  2,827 lines

  1. % This program by D. E. Knuth is not copyrighted and can be used freely.
  2. % Version 0 was released in December, 1981.
  3. % Version 1 was released in September, 1982, with version 0 of TeX.
  4. % Slight changes were made in October, 1982, for version 0.6 of TeX.
  5. % Version 1.2 added @@= and @@\ and introduced {:nnn} comments (December, 1982).
  6. % Version 1.4 added "history" (February, 1983).
  7. % Version 1.5 conformed to TeX version 0.96 and fixed @@\ (March, 1983).
  8. % Version 1.7 introduced the new change file format (June, 1983).
  9. % Version 2.0 was released in July, 1983, with version 0.999 of TeX.
  10. % Version 2.5 was released in November, 1983, with version 1.0 of TeX.
  11. % Version 2.6 fixed a bug: force-line-break after a constant (August, 1984).
  12. % Version 2.7 fixed the definition of check_sum_prime (May, 1985).
  13. % Version 2.8 fixed a bug in change_buffer movement (August, 1985).
  14. % Version 2.9 allows nonnumeric macros before their def (December, 1988).
  15. % Version 3, for Sewell's book, fixed long-line bug in input_ln (March, 1989).
  16. % Version 4 was major change to allow 8-bit input (September, 1989).
  17. % Here is TeX material that gets inserted after \input webmac
  18. \def\hang{\hangindent 3em\indent\ignorespaces}
  19. \font\ninerm=cmr9
  20. \let\mc=\ninerm % medium caps for names like SAIL
  21. \def\PASCAL{Pascal}
  22. \def\pb{$\.|\ldots\.|$} % Pascal brackets (|...|)
  23. \def\v{\.{\char'174}} % vertical (|) in typewriter font
  24. \mathchardef\BA="3224 % double arrow
  25. \def\({} % kludge for alphabetizing certain module names
  26. \def\title{TANGLE}
  27. \def\contentspagenumber{123} % should be odd
  28. \def\topofcontents{\null\vfill
  29.   \titlefalse % include headline on the contents page
  30.   \def\rheader{\mainfont Appendix E\hfil \contentspagenumber}
  31.   \centerline{\titlefont The {\ttitlefont TANGLE} processor}
  32.   \vskip 15pt
  33.   \centerline{(Version 4)}
  34.   \vfill}
  35. \pageno=\contentspagenumber \advance\pageno by 1
  36. @* Introduction.
  37. This program converts a \.{WEB} file to a \PASCAL\ file. It was written
  38. by D. E. Knuth in September, 1981; a somewhat similar {\mc SAIL} program had
  39. been developed in March, 1979. Since this program describes itself, a
  40. bootstrapping process involving hand-translation had to be used to get started.
  41. For large \.{WEB} files one should have a large memory, since \.{TANGLE} keeps
  42. all the \PASCAL\ text in memory (in an abbreviated form). The program uses
  43. a few features of the local \PASCAL\ compiler that may need to be changed in
  44. other installations:
  45. \yskip\item{1)} Case statements have a default.
  46. \item{2)} Input-output routines may need to be adapted for use with a particular
  47. character set and/or for printing messages on the user's terminal.
  48. \yskip\noindent
  49. These features are also present in the \PASCAL\ version of \TeX, where they
  50. are used in a similar (but more complex) way. System-dependent portions
  51. of \.{TANGLE} can be identified by looking at the entries for `system
  52. dependencies' in the index below.
  53. @!@^system dependencies@>
  54. The ``banner line'' defined here should be changed whenever \.{TANGLE}
  55. is modified.
  56. @d banner=='This is TANGLE, Version 4'
  57. @ The program begins with a fairly normal header, made up of pieces that
  58. @^system dependencies@>
  59. will mostly be filled in later. The \.{WEB} input comes from files |web_file|
  60. and |change_file|, the \PASCAL\ output goes to file |Pascal_file|,
  61. and the string pool output goes to file |pool|.
  62. If it is necessary to abort the job because of a fatal error, the program
  63. calls the `|jump_out|' procedure, which goes to the label |end_of_TANGLE|.
  64. @d end_of_TANGLE = 9999 {go here to wrap it up}
  65. @p @t\4@>@<Compiler directives@>@/
  66. program TANGLE(@!web_file,@!change_file,@!Pascal_file,@!pool);
  67. label end_of_TANGLE; {go here to finish}
  68. const @<Constants in the outer block@>@/
  69. type @<Types in the outer block@>@/
  70. var @<Globals in the outer block@>@/
  71. @<Error handling procedures@>@/
  72. procedure initialize;
  73.   var @<Local variables for initialization@>@/
  74.   begin @<Set initial values@>@/
  75.   end;
  76. @ Some of this code is optional for use when debugging only;
  77. such material is enclosed between the delimiters |debug| and $|gubed|$.
  78. Other parts, delimited by |stat| and $|tats|$, are optionally included if
  79. statistics about \.{TANGLE}'s memory usage are desired.
  80. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  81. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  82. @f debug==begin
  83. @f gubed==end
  84. @d stat==@{ {change this to `$\\{stat}\equiv\null$'
  85.   when gathering usage statistics}
  86. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$'
  87.   when gathering usage statistics}
  88. @f stat==begin
  89. @f tats==end
  90. @ The \PASCAL\ compiler used to develop this system has ``compiler
  91. directives'' that can appear in comments whose first character is a dollar sign.
  92. In production versions of \.{TANGLE} these directives tell the compiler that
  93. @^system dependencies@>
  94. it is safe to avoid range checks and to leave out the extra code it inserts
  95. for the \PASCAL\ debugger's benefit, although interrupts will occur if
  96. there is arithmetic overflow.
  97. @<Compiler directives@>=
  98. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  99. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  100. @ Labels are given symbolic names by the following definitions. We insert
  101. the label `|exit|:' just before the `\ignorespaces|end|\unskip' of a
  102. procedure in which we have used the `|return|' statement defined below;
  103. the label `|restart|' is occasionally used at the very beginning of a
  104. procedure; and the label `|reswitch|' is occasionally used just prior to
  105. a \&{case} statement in which some cases change the conditions and we wish to
  106. branch to the newly applicable case.
  107. Loops that are set up with the \&{loop} construction defined below are
  108. commonly exited by going to `|done|' or to `|found|' or to `|not_found|',
  109. and they are sometimes repeated by going to `|continue|'.
  110. @d exit=10 {go here to leave a procedure}
  111. @d restart=20 {go here to start a procedure again}
  112. @d reswitch=21 {go here to start a case statement again}
  113. @d continue=22 {go here to resume a loop}
  114. @d done=30 {go here to exit a loop}
  115. @d found=31 {go here when you've found it}
  116. @d not_found=32 {go here when you've found something else}
  117. @ Here are some macros for common programming idioms.
  118. @d incr(#) == #:=#+1 {increase a variable by unity}
  119. @d decr(#) == #:=#-1 {decrease a variable by unity}
  120. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  121. @d do_nothing == {empty statement}
  122. @d return == goto exit {terminate a procedure call}
  123. @f return == nil
  124. @f loop == xclause
  125. @ We assume that |case| statements may include a default case that applies
  126. if no matching label is found. Thus, we shall use constructions like
  127. @^system dependencies@>
  128. $$\vbox{\halign{#\hfil\cr
  129. |case x of|\cr
  130. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  131. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  132. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  133. |endcases|\cr}}$$
  134. since most \PASCAL\ compilers have plugged this hole in the language by
  135. incorporating some sort of default mechanism. For example, the compiler
  136. used to develop \.{WEB} and \TeX\ allows `|others|:' as a default label,
  137. and other \PASCAL s allow syntaxes like `\ignorespaces|else|\unskip' or
  138. `\&{otherwise}' or `\\{otherwise}:', etc. The definitions of |othercases|
  139. and |endcases| should be changed to agree with local conventions. (Of
  140. course, if no default mechanism is available, the |case| statements of
  141. this program must be extended by listing all remaining cases. The author
  142. would have taken the trouble to modify \.{TANGLE} so that such extensions
  143. were done automatically, if he had not wanted to encourage \PASCAL\
  144. compiler writers to make this important change in \PASCAL, where it belongs.)
  145. @d othercases == others: {default for cases not listed explicitly}
  146. @d endcases == @+end {follows the default case in an extended |case| statement}
  147. @f othercases == else
  148. @f endcases == end
  149. @ The following parameters are set big enough to handle \TeX, so they
  150. should be sufficient for most applications of \.{TANGLE}.
  151. @<Constants...@>=
  152. @!buf_size=100; {maximum length of input line}
  153. @!max_bytes=45000; {|1/ww| times the number of bytes in identifiers,
  154.   strings, and module names; must be less than 65536}
  155. @!max_toks=50000; {|1/zz| times the number of bytes in compressed \PASCAL\ code;
  156.   must be less than 65536}
  157. @!max_names=4000; {number of identifiers, strings, module names;
  158.   must be less than 10240}
  159. @!max_texts=2000; {number of replacement texts, must be less than 10240}
  160. @!hash_size=353; {should be prime}
  161. @!longest_name=400; {module names shouldn't be longer than this}
  162. @!line_length=72; {lines of \PASCAL\ output have at most this many characters}
  163. @!out_buf_size=144; {length of output buffer, should be twice |line_length|}
  164. @!stack_size=50; {number of simultaneous levels of macro expansion}
  165. @!max_id_length=12; {long identifiers are chopped to this length, which must
  166.   not exceed |line_length|}
  167. @!unambig_length=7; {identifiers must be unique if chopped to this length}
  168.   {note that 7 is more strict than \PASCAL's 8, but this can be varied}
  169. @ A global variable called |history| will contain one of four values
  170. at the end of every run: |spotless| means that no unusual messages were
  171. printed; |harmless_message| means that a message of possible interest
  172. was printed but no serious errors were detected; |error_message| means that
  173. at least one error was found; |fatal_message| means that the program
  174. terminated abnormally. The value of |history| does not influence the
  175. behavior of the program; it is simply computed for the convenience
  176. of systems that might want to use such information.
  177. @d spotless=0 {|history| value for normal jobs}
  178. @d harmless_message=1 {|history| value when non-serious info was printed}
  179. @d error_message=2 {|history| value when an error was noted}
  180. @d fatal_message=3 {|history| value when we had to stop prematurely}
  181. @d mark_harmless==@t@>@+if history=spotless then history:=harmless_message
  182. @d mark_error==history:=error_message
  183. @d mark_fatal==history:=fatal_message
  184. @<Glob...@>=@!history:spotless..fatal_message; {how bad was this run?}
  185. @ @<Set init...@>=history:=spotless;
  186. @* The character set.
  187. One of the main goals in the design of \.{WEB} has been to make it readily
  188. portable between a wide variety of computers. Yet \.{WEB} by its very
  189. nature must use a greater variety of characters than most computer
  190. programs deal with, and character encoding is one of the areas in which
  191. existing machines differ most widely from each other.
  192. To resolve this problem, all input to \.{WEAVE} and \.{TANGLE} is converted
  193. to an internal eight-bit code that is essentially standard ASCII, the ``American
  194. Standard Code for Information Interchange.''  The conversion is done
  195. immediately when each character is read in. Conversely, characters are
  196. converted from ASCII to the user's external representation just before
  197. they are output. (The original ASCII code was seven bits only; \.{WEB} now
  198. allows eight bits in an attempt to keep up with modern times.)
  199. Such an internal code is relevant to users of \.{WEB} only because it is
  200. the code used for preprocessed constants like \.{"A"}. If you are writing
  201. a program in \.{WEB} that makes use of such one-character constants, you
  202. should convert your input to ASCII form, like \.{WEAVE} and \.{TANGLE} do.
  203. Otherwise \.{WEB}'s internal coding scheme does not affect you.
  204. @^ASCII code@>
  205. Here is a table of the standard visible ASCII codes:
  206. $$\def\:{\char\count255\global\advance\count255 by 1}
  207. \count255='40
  208. \vbox{
  209. \hbox{\hbox to 40pt{\it\hfill0\/\hfill}%
  210. \hbox to 40pt{\it\hfill1\/\hfill}%
  211. \hbox to 40pt{\it\hfill2\/\hfill}%
  212. \hbox to 40pt{\it\hfill3\/\hfill}%
  213. \hbox to 40pt{\it\hfill4\/\hfill}%
  214. \hbox to 40pt{\it\hfill5\/\hfill}%
  215. \hbox to 40pt{\it\hfill6\/\hfill}%
  216. \hbox to 40pt{\it\hfill7\/\hfill}}
  217. \vskip 4pt
  218. \hrule
  219. \def\^{\vrule height 10.5pt depth 4.5pt}
  220. \halign{\hbox to 0pt{\hskip -24pt\O{#0}\hfill}&\^
  221. \hbox to 40pt{\tt\hfill#\hfill\^}&
  222. &\hbox to 40pt{\tt\hfill#\hfill\^}\cr
  223. 04&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  224. 05&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  225. 06&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  226. 07&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  227. 10&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  228. 11&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  229. 12&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  230. 13&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  231. 14&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  232. 15&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  233. 16&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  234. 17&\:&\:&\:&\:&\:&\:&\:\cr}
  235. \hrule width 280pt}$$
  236. (Actually, of course, code @'040 is an invisible blank space.)  Code @'136
  237. was once an upward arrow (\.{\char'13}), and code @'137 was
  238. once a left arrow (\.^^X), in olden times when the first draft
  239. of ASCII code was prepared; but \.{WEB} works with today's standard
  240. ASCII in which those codes represent circumflex and underline as shown.
  241. @<Types...@>=
  242. @!ASCII_code=0..255; {eight-bit numbers, a subrange of the integers}
  243. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  244. character sets were common, so it did not make provision for lowercase
  245. letters. Nowadays, of course, we need to deal with both capital and small
  246. letters in a convenient way, so \.{WEB} assumes that it is being used
  247. with a \PASCAL\ whose character set contains at least the characters of
  248. standard ASCII as listed above. Some \PASCAL\ compilers use the original
  249. name |char| for the data type associated with the characters in text files,
  250. while other \PASCAL s consider |char| to be a 64-element subrange of a larger
  251. data type that has some other name.
  252. In order to accommodate this difference, we shall use the name |text_char|
  253. to stand for the data type of the characters in the input and output
  254. files.  We shall also assume that |text_char| consists of the elements
  255. |chr(first_text_char)| through |chr(last_text_char)|, inclusive. The
  256. following definitions should be adjusted if necessary.
  257. @^system dependencies@>
  258. @d text_char == char {the data type of characters in text files}
  259. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  260. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  261. @<Types...@>=
  262. @!text_file=packed file of text_char;
  263. @ The \.{WEAVE} and \.{TANGLE} processors convert between ASCII code and
  264. the user's external character set by means of arrays |xord| and |xchr|
  265. that are analogous to \PASCAL's |ord| and |chr| functions.
  266. @<Globals...@>=
  267. @!xord: array [text_char] of ASCII_code;
  268.   {specifies conversion of input characters}
  269. @!xchr: array [ASCII_code] of text_char;
  270.   {specifies conversion of output characters}
  271. @ If we assume that every system using \.{WEB} is able to read and write the
  272. visible characters of standard ASCII (although not necessarily using the
  273. ASCII codes to represent them), the following assignment statements initialize
  274. most of the |xchr| array properly, without needing any system-dependent
  275. changes. For example, the statement \.{xchr[@@\'101]:=\'A\'} that appears
  276. in the present \.{WEB} file might be encoded in, say, {\mc EBCDIC} code
  277. on the external medium on which it resides, but \.{TANGLE} will convert from
  278. this external code to ASCII and back again. Therefore the assignment
  279. statement \.{XCHR[65]:=\'A\'} will appear in the corresponding \PASCAL\ file,
  280. and \PASCAL\ will compile this statement so that |xchr[65]| receives the
  281. character \.A in the external (|char|) code. Note that it would be quite
  282. incorrect to say \.{xchr[@@\'101]:="A"}, because |"A"| is a constant of
  283. type |integer|, not |char|, and because we have $|"A"|=65$ regardless of
  284. the external character set.
  285. @<Set init...@>=
  286. xchr[@'40]:=' ';
  287. xchr[@'41]:='!';
  288. xchr[@'42]:='"';
  289. xchr[@'43]:='#';
  290. xchr[@'44]:='$';
  291. xchr[@'45]:='%';
  292. xchr[@'46]:='&';
  293. xchr[@'47]:='''';@/
  294. xchr[@'50]:='(';
  295. xchr[@'51]:=')';
  296. xchr[@'52]:='*';
  297. xchr[@'53]:='+';
  298. xchr[@'54]:=',';
  299. xchr[@'55]:='-';
  300. xchr[@'56]:='.';
  301. xchr[@'57]:='/';@/
  302. xchr[@'60]:='0';
  303. xchr[@'61]:='1';
  304. xchr[@'62]:='2';
  305. xchr[@'63]:='3';
  306. xchr[@'64]:='4';
  307. xchr[@'65]:='5';
  308. xchr[@'66]:='6';
  309. xchr[@'67]:='7';@/
  310. xchr[@'70]:='8';
  311. xchr[@'71]:='9';
  312. xchr[@'72]:=':';
  313. xchr[@'73]:=';';
  314. xchr[@'74]:='<';
  315. xchr[@'75]:='=';
  316. xchr[@'76]:='>';
  317. xchr[@'77]:='?';@/
  318. xchr[@'100]:='@@';
  319. xchr[@'101]:='A';
  320. xchr[@'102]:='B';
  321. xchr[@'103]:='C';
  322. xchr[@'104]:='D';
  323. xchr[@'105]:='E';
  324. xchr[@'106]:='F';
  325. xchr[@'107]:='G';@/
  326. xchr[@'110]:='H';
  327. xchr[@'111]:='I';
  328. xchr[@'112]:='J';
  329. xchr[@'113]:='K';
  330. xchr[@'114]:='L';
  331. xchr[@'115]:='M';
  332. xchr[@'116]:='N';
  333. xchr[@'117]:='O';@/
  334. xchr[@'120]:='P';
  335. xchr[@'121]:='Q';
  336. xchr[@'122]:='R';
  337. xchr[@'123]:='S';
  338. xchr[@'124]:='T';
  339. xchr[@'125]:='U';
  340. xchr[@'126]:='V';
  341. xchr[@'127]:='W';@/
  342. xchr[@'130]:='X';
  343. xchr[@'131]:='Y';
  344. xchr[@'132]:='Z';
  345. xchr[@'133]:='[';
  346. xchr[@'134]:='\';
  347. xchr[@'135]:=']';
  348. xchr[@'136]:='^';
  349. xchr[@'137]:='_';@/
  350. xchr[@'140]:='`';
  351. xchr[@'141]:='a';
  352. xchr[@'142]:='b';
  353. xchr[@'143]:='c';
  354. xchr[@'144]:='d';
  355. xchr[@'145]:='e';
  356. xchr[@'146]:='f';
  357. xchr[@'147]:='g';@/
  358. xchr[@'150]:='h';
  359. xchr[@'151]:='i';
  360. xchr[@'152]:='j';
  361. xchr[@'153]:='k';
  362. xchr[@'154]:='l';
  363. xchr[@'155]:='m';
  364. xchr[@'156]:='n';
  365. xchr[@'157]:='o';@/
  366. xchr[@'160]:='p';
  367. xchr[@'161]:='q';
  368. xchr[@'162]:='r';
  369. xchr[@'163]:='s';
  370. xchr[@'164]:='t';
  371. xchr[@'165]:='u';
  372. xchr[@'166]:='v';
  373. xchr[@'167]:='w';@/
  374. xchr[@'170]:='x';
  375. xchr[@'171]:='y';
  376. xchr[@'172]:='z';
  377. xchr[@'173]:='{';
  378. xchr[@'174]:='|';
  379. xchr[@'175]:='}';
  380. xchr[@'176]:='~';@/
  381. xchr[0]:=' '; xchr[@'177]:=' '; {these ASCII codes are not used}
  382. @ Some of the ASCII codes below @'40 have been given symbolic names in
  383. \.{WEAVE} and \.{TANGLE} because they are used with a special meaning.
  384. @d and_sign=@'4 {equivalent to `\.{and}'}
  385. @d not_sign=@'5 {equivalent to `\.{not}'}
  386. @d set_element_sign=@'6 {equivalent to `\.{in}'}
  387. @d tab_mark=@'11 {ASCII code used as tab-skip}
  388. @d line_feed=@'12 {ASCII code thrown away at end of line}
  389. @d form_feed=@'14 {ASCII code used at end of page}
  390. @d carriage_return=@'15 {ASCII code used at end of line}
  391. @d left_arrow=@'30 {equivalent to `\.{:=}'}
  392. @d not_equal=@'32 {equivalent to `\.{<>}'}
  393. @d less_or_equal=@'34 {equivalent to `\.{<=}'}
  394. @d greater_or_equal=@'35 {equivalent to `\.{>=}'}
  395. @d equivalence_sign=@'36 {equivalent to `\.{==}'}
  396. @d or_sign=@'37 {equivalent to `\.{or}'}
  397. @ When we initialize the |xord| array and the remaining parts of |xchr|,
  398. it will be convenient to make use of an index variable, |i|.
  399. @<Local variables for init...@>=
  400. @!i:0..255;
  401. @ Here now is the system-dependent part of the character set.
  402. If \.{WEB} is being implemented on a garden-variety \PASCAL\ for which
  403. only standard ASCII codes will appear in the input and output files, you
  404. don't need to make any changes here. But if you have, for example, an extended
  405. character set like the one in Appendix~C of {\sl The \TeX book}, the first
  406. line of code in this module should be changed to
  407. $$\hbox{|for i:=1 to @'37 do xchr[i]:=chr(i);|}$$
  408. \.{WEB}'s character set is essentially identical to \TeX's, even with respect to
  409. characters less than @'40.
  410. @^system dependencies@>
  411. Changes to the present module will make \.{WEB} more friendly on computers
  412. that have an extended character set, so that one can type things like
  413. \.^^Z\ instead of \.{<>}. If you have an extended set of characters that
  414. are easily incorporated into text files, you can assign codes arbitrarily
  415. here, giving an |xchr| equivalent to whatever characters the users of
  416. \.{WEB} are allowed to have in their input files, provided that unsuitable
  417. characters do not correspond to special codes like |carriage_return|
  418. that are listed above.
  419. (The present file \.{TANGLE.WEB} does not contain any of the non-ASCII
  420. characters, because it is intended to be used with all implementations of
  421. \.{WEB}.  It was originally created on a Stanford system that has a
  422. convenient extended character set, then ``sanitized'' by applying another
  423. program that transliterated all of the non-standard characters into
  424. standard equivalents.)
  425. @<Set init...@>=
  426. for i:=1 to @'37 do xchr[i]:=' ';
  427. for i:=@'200 to @'377 do xchr[i]:=' ';
  428. @ The following system-independent code makes the |xord| array contain a
  429. suitable inverse to the information in |xchr|.
  430. @<Set init...@>=
  431. for i:=first_text_char to last_text_char do xord[chr(i)]:=" ";
  432. for i:=1 to @'377 do xord[xchr[i]]:=i;
  433. xord[' ']:=" ";
  434. @* Input and output.
  435. The input conventions of this program are intended to be very much like those
  436. of \TeX\ (except, of course, that they are much simpler, because much less
  437. needs to be done). Furthermore they are identical to those of \.{WEAVE}.
  438. Therefore people who need to make modifications to all three systems
  439. should be able to do so without too many headaches.
  440. We use the standard \PASCAL\ input/output procedures in several places that
  441. \TeX\ cannot, since \.{TANGLE} does not have to deal with files that are named
  442. dynamically by the user, and since there is no input from the terminal.
  443. @ Terminal output is done by writing on file |term_out|, which is assumed to
  444. consist of characters of type |text_char|:
  445. @^system dependencies@>
  446. @d print(#)==write(term_out,#) {`|print|' means write on the terminal}
  447. @d print_ln(#)==write_ln(term_out,#) {`|print|' and then start new line}
  448. @d new_line==write_ln(term_out) {start new line}
  449. @d print_nl(#)==  {print information starting on a new line}
  450.   begin new_line; print(#);
  451.   end
  452. @<Globals...@>=
  453. @!term_out:text_file; {the terminal as an output file}
  454. @ Different systems have different ways of specifying that the output on a
  455. certain file will appear on the user's terminal. Here is one way to do this
  456. on the \PASCAL\ system that was used in \.{TANGLE}'s initial development:
  457. @^system dependencies@>
  458. @<Set init...@>=
  459. rewrite(term_out,'TTY:'); {send |term_out| output to the terminal}
  460. @ The |update_terminal| procedure is called when we want
  461. to make sure that everything we have output to the terminal so far has
  462. actually left the computer's internal buffers and been sent.
  463. @^system dependencies@>
  464. @d update_terminal == break(term_out) {empty the terminal output buffer}
  465. @ The main input comes from |web_file|; this input may be overridden
  466. by changes in |change_file|. (If |change_file| is empty, there are no changes.)
  467. @<Globals...@>=
  468. @!web_file:text_file; {primary input}
  469. @!change_file:text_file; {updates}
  470. @ The following code opens the input files.  Since these files were listed
  471. in the program header, we assume that the \PASCAL\ runtime system has
  472. already checked that suitable file names have been given; therefore no
  473. additional error checking needs to be done.
  474. @^system dependencies@>
  475. @p procedure open_input; {prepare to read |web_file| and |change_file|}
  476. begin reset(web_file); reset(change_file);
  477. @ The main output goes to |Pascal_file|, and string pool constants are
  478. written to the |pool| file.
  479. @<Globals...@>=
  480. @!Pascal_file: text_file;
  481. @!pool: text_file;
  482. @ The following code opens |Pascal_file| and |pool|.
  483. Since these files were listed in the program header, we assume that the
  484. \PASCAL\ runtime system has checked that suitable external file names have
  485. been given.
  486. @^system dependencies@>
  487. @<Set init...@>=
  488. rewrite(Pascal_file); rewrite(pool);
  489. @ Input goes into an array called |buffer|.
  490. @<Globals...@>=@!buffer: array[0..buf_size] of ASCII_code;
  491. @ The |input_ln| procedure brings the next line of input from the specified
  492. file into the |buffer| array and returns the value |true|, unless the file has
  493. already been entirely read, in which case it returns |false|. The conventions
  494. of \TeX\ are followed; i.e., |ASCII_code| numbers representing the next line
  495. of the file are input into |buffer[0]|, |buffer[1]|, \dots,
  496. |buffer[limit-1]|; trailing blanks are ignored;
  497. and the global variable |limit| is set to the length of the
  498. @^system dependencies@>
  499. line. The value of |limit| must be strictly less than |buf_size|.
  500. We assume that none of the |ASCII_code| values
  501. of |buffer[j]| for |0<=j<limit| is equal to 0, @'177, |line_feed|, |form_feed|,
  502. or |carriage_return|.
  503. @p function input_ln(var f:text_file):boolean;
  504.   {inputs a line or returns |false|}
  505. var final_limit:0..buf_size; {|limit| without trailing blanks}
  506. begin limit:=0; final_limit:=0;
  507. if eof(f) then input_ln:=false
  508. else  begin while not eoln(f) do
  509.     begin buffer[limit]:=xord[f^]; get(f);
  510.     incr(limit);
  511.     if buffer[limit-1]<>" " then final_limit:=limit;
  512.     if limit=buf_size then
  513.       begin while not eoln(f) do get(f);
  514.       decr(limit); {keep |buffer[buf_size]| empty}
  515.       if final_limit>limit then final_limit:=limit;
  516.       print_nl('! Input line too long'); loc:=0; error;
  517. @.Input line too long@>
  518.       end;
  519.     end;
  520.   read_ln(f); limit:=final_limit; input_ln:=true;
  521.   end;
  522. @* Reporting errors to the user.
  523. The \.{TANGLE} processor operates in two phases: first it inputs the source
  524. file and stores a compressed representation of the program, then it produces
  525. the \PASCAL\ output from the compressed representation.
  526. The global variable |phase_one| tells whether we are in Phase I or not.
  527. @<Globals...@>=
  528. @!phase_one: boolean; {|true| in Phase I, |false| in Phase II}
  529. @ If an error is detected while we are debugging,
  530. we usually want to look at the contents of memory.
  531. A special procedure will be declared later for this purpose.
  532. @<Error handling...@>=
  533. @!debug @+ procedure debug_help; forward;@+ gubed
  534. @ During the first phase, syntax errors are reported to the user by saying
  535. $$\hbox{`|err_print('! Error message')|'},$$
  536. followed by `|jump_out|' if no recovery from the error is provided.
  537. This will print the error message followed by an indication of where the error
  538. was spotted in the source file. Note that no period follows the error message,
  539. since the error routine will automatically supply a period.
  540. Errors that are noticed during the second phase are reported to the user
  541. in the same fashion, but the error message will be
  542. followed by an indication of where the error was spotted in the output file.
  543. The actual error indications are provided by a procedure called |error|.
  544. @d err_print(#)==begin new_line; print(#); error;
  545.   end
  546. @<Error handling...@>=
  547. procedure error; {prints '\..' and location of error message}
  548. var j: 0..out_buf_size; {index into |out_buf|}
  549. @!k,@!l: 0..buf_size; {indices into |buffer|}
  550. begin if phase_one then @<Print error location based on input buffer@>
  551. else @<Print error location based on output buffer@>;
  552. update_terminal; mark_error;
  553. @!debug debug_help;@+gubed
  554. @ The error locations during Phase I can be indicated by using the global
  555. variables |loc|, |line|, and |changing|, which tell respectively the first
  556. unlooked-at position in |buffer|, the current line number, and whether or not
  557. the current line is from |change_file| or |web_file|.
  558. This routine should be modified on systems whose standard text editor
  559. has special line-numbering conventions.
  560. @^system dependencies@>
  561. @<Print error location based on input buffer@>=
  562. begin if changing then print('. (change file ')@+else print('. (');
  563. print_ln('l.', line:1, ')');
  564. if loc>=limit then l:=limit else l:=loc;
  565. for k:=1 to l do
  566.   if buffer[k-1]=tab_mark then print(' ')
  567.   else print(xchr[buffer[k-1]]); {print the characters already read}
  568. new_line;
  569. for k:=1 to l do print(' '); {space out the next line}
  570. for k:=l+1 to limit do print(xchr[buffer[k-1]]); {print the part not yet read}
  571. print(' '); {this space separates the message from future asterisks}
  572. @ The position of errors detected during the second phase can be indicated
  573. by outputting the partially-filled output buffer, which contains |out_ptr|
  574. entries.
  575. @<Print error location based on output...@>=
  576. begin print_ln('. (l.',line:1,')');
  577. for j:=1 to out_ptr do print(xchr[out_buf[j-1]]); {print current partial line}
  578. print('... '); {indicate that this information is partial}
  579. @ The |jump_out| procedure just cuts across all active procedure levels
  580. and jumps out of the program. This is the only non-local |goto| statement
  581. in \.{TANGLE}. It is used when no recovery from a particular error has
  582. been provided.
  583. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  584. @^system dependencies@>
  585. In such cases the code that appears at label |end_of_TANGLE| should be
  586. copied into the |jump_out| procedure, followed by a call to a system procedure
  587. that terminates the program.
  588. @d fatal_error(#)==begin new_line; print(#); error; mark_fatal; jump_out;
  589.   end
  590. @<Error handling...@>=
  591. procedure jump_out;
  592. begin goto end_of_TANGLE;
  593. @ Sometimes the program's behavior is far different from what it should be,
  594. and \.{TANGLE} prints an error message that is really for the \.{TANGLE}
  595. maintenance person, not the user. In such cases the program says
  596. |confusion('indication of where we are')|.
  597. @d confusion(#)==fatal_error('! This can''t happen (',#,')')
  598. @.This can't happen@>
  599. @ An overflow stop occurs if \.{TANGLE}'s tables aren't large enough.
  600. @d overflow(#)==fatal_error('! Sorry, ',#,' capacity exceeded')
  601. @.Sorry, x capacity exceeded@>
  602. @* Data structures.
  603. Most of the user's \PASCAL\ code is packed into eight-bit integers
  604. in two large arrays called |byte_mem| and |tok_mem|.
  605. The |byte_mem| array holds the names of identifiers, strings, and modules;
  606. the |tok_mem| array holds the replacement texts
  607. for macros and modules. Allocation is sequential, since things are deleted only
  608. during Phase II, and only in a last-in-first-out manner.
  609. Auxiliary arrays |byte_start| and |tok_start| are used as directories to
  610. |byte_mem| and |tok_mem|, and the |link|, |ilk|, |equiv|, and |text_link|
  611. arrays give further information about names. These auxiliary arrays
  612. consist of sixteen-bit items.
  613. @<Types...@>=
  614. @!eight_bits=0..255; {unsigned one-byte quantity}
  615. @!sixteen_bits=0..65535; {unsigned two-byte quantity}
  616. @ \.{TANGLE} has been designed to avoid the need for indices that are more
  617. than sixteen bits wide, so that it can be used on most computers. But
  618. there are programs that need more than 65536 tokens, and some programs
  619. even need more than 65536 bytes; \TeX\ is one of these.  To get around
  620. this problem, a slight complication has been added to the data structures:
  621. |byte_mem| and |tok_mem| are two-dimensional arrays, whose first index is
  622. either 0 or 1. (For generality, the first index is actually allowed to run
  623. between 0 and |ww-1| in |byte_mem|, or between 0 and |zz-1| in |tok_mem|,
  624. where |ww| and |zz| are set to 2 and~3; the program will work for any
  625. positive values of |ww| and |zz|, and it can be simplified in obvious ways
  626. if |ww=1| or |zz=1|.)
  627. @d ww=2 {we multiply the byte capacity by approximately this amount}
  628. @d zz=3 {we multiply the token capacity by approximately this amount}
  629. @<Globals...@>=
  630. @!byte_mem: packed array [0..ww-1,0..max_bytes] of ASCII_code;
  631.   {characters of names}
  632. @!tok_mem: packed array [0..zz-1,0..max_toks] of eight_bits; {tokens}
  633. @!byte_start: array [0..max_names] of sixteen_bits; {directory into |byte_mem|}
  634. @!tok_start: array [0..max_texts] of sixteen_bits; {directory into |tok_mem|}
  635. @!link: array [0..max_names] of sixteen_bits; {hash table or tree links}
  636. @!ilk: array [0..max_names] of sixteen_bits; {type codes or tree links}
  637. @!equiv: array [0..max_names] of sixteen_bits; {info corresponding to names}
  638. @!text_link: array [0..max_texts] of sixteen_bits; {relates replacement texts}
  639. @ The names of identifiers are found by computing a hash address |h| and
  640. then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
  641. |link[link[hash[h]]]|, \dots, until either finding the desired name
  642. or encountering a zero.
  643. A `|name_pointer|' variable, which signifies a name, is an index into
  644. |byte_start|. The actual sequence of characters in the name pointed to by
  645. |p| appears in positions |byte_start[p]| to |byte_start[p+ww]-1|, inclusive,
  646. in the segment of |byte_mem| whose first index is |p mod ww|. Thus, when
  647. |ww=2| the even-numbered name bytes appear in |byte_mem[0,@t$*$@>]|
  648. and the odd-numbered ones appear in |byte_mem[1,@t$*$@>]|.
  649. The pointer 0 is used for undefined module names; we don't
  650. want to use it for the names of identifiers, since 0 stands for a null
  651. pointer in a linked list.
  652. Strings are treated like identifiers; the first character (a double-quote)
  653. distinguishes a string from an alphabetic name, but for \.{TANGLE}'s purposes
  654. strings behave like numeric macros. (A `string' here refers to the
  655. strings delimited by double-quotes that \.{TANGLE} processes. \PASCAL\
  656. string constants delimited by single-quote marks are not given such special
  657. treatment; they simply appear as sequences of characters in the \PASCAL\
  658. texts.)  The total number of strings in the string
  659. pool is called |string_ptr|, and the total number of names in |byte_mem|
  660. is called |name_ptr|. The total number of bytes occupied in
  661. |byte_mem[w,@t$*$@>]| is called |byte_ptr[w]|.
  662. We usually have |byte_start[name_ptr+w]=byte_ptr[(name_ptr+w) mod ww]|
  663. for |0<=w<ww|, since these are the starting positions for the next |ww|
  664. names to be stored in |byte_mem|.
  665. @d length(#)==byte_start[#+ww]-byte_start[#] {the length of a name}
  666. @<Types...@>=
  667. @!name_pointer=0..max_names; {identifies a name}
  668. @ @<Global...@>=
  669. @!name_ptr:name_pointer; {first unused position in |byte_start|}
  670. @!string_ptr:name_pointer; {next number to be given to a string of length |<>1|}
  671. @!byte_ptr:array [0..ww-1] of 0..max_bytes;
  672.   {first unused position in |byte_mem|}
  673. @!pool_check_sum:integer; {sort of a hash for the whole string pool}
  674. @ @<Local variables for init...@>=
  675. @!wi: 0..ww-1; {to initialize the |byte_mem| indices}
  676. @ @<Set init...@>=
  677. for wi:=0 to ww-1 do
  678.   begin byte_start[wi]:=0; byte_ptr[wi]:=0;
  679.   end;
  680. byte_start[ww]:=0; {this makes name 0 of length zero}
  681. name_ptr:=1; string_ptr:=256; pool_check_sum:=271828;
  682. @ Replacement texts are stored in |tok_mem|, using similar conventions.
  683. A `|text_pointer|' variable is an index into |tok_start|, and the
  684. replacement text that corresponds to |p| runs from positions
  685. |tok_start[p]| to |tok_start[p+zz]-1|, inclusive, in the segment of
  686. |tok_mem| whose first index is |p mod zz|. Thus, when |zz=2| the
  687. even-numbered replacement texts appear in |tok_mem[0,@t$*$@>]| and the
  688. odd-numbered ones appear in |tok_mem[1,@t$*$@>]|.  Furthermore,
  689. |text_link[p]| is used to connect pieces of text that have the same name,
  690. as we shall see later. The pointer 0 is used for undefined replacement
  691. texts.
  692. The first position of |tok_mem[z,@t$*$@>]| that is unoccupied by
  693. replacement text is called |tok_ptr[z]|, and the first unused location of
  694. |tok_start| is called |text_ptr|.  We usually have the identity
  695. |tok_start[text_ptr+z]=tok_ptr[(text_ptr+z) mod zz]|, for |0<=z<zz|, since
  696. these are the starting positions for the next |zz| replacement texts to
  697. be stored in |tok_mem|.
  698. @<Types...@>=
  699. @!text_pointer=0..max_texts; {identifies a replacement text}
  700. @ It is convenient to maintain a variable |z| that is equal to |text_ptr
  701. mod zz|, so that we always insert tokens into segment |z| of |tok_mem|.
  702. @<Glob...@>=
  703. @t\hskip1em@>@!text_ptr:text_pointer; {first unused position in |tok_start|}
  704. @t\hskip1em@>@!tok_ptr:array[0..zz-1] of 0..max_toks;
  705.   {first unused position in a given segment of |tok_mem|}
  706. @t\hskip1em@>@!z:0..zz-1; {current segment of |tok_mem|}
  707. stat @!max_tok_ptr:array[0..zz-1] of 0..max_toks;
  708.   {largest values assumed by |tok_ptr|}
  709. @ @<Local variables for init...@>=
  710. @!zi:0..zz-1; {to initialize the |tok_mem| indices}
  711. @ @<Set init...@>=
  712. for zi:=0 to zz-1 do
  713.   begin tok_start[zi]:=0; tok_ptr[zi]:=0;
  714.   end;
  715. tok_start[zz]:=0; {this makes replacement text 0 of length zero}
  716. text_ptr:=1; z:=1 mod zz;
  717. @ Four types of identifiers are distinguished by their |ilk|:
  718. \yskip\hang |normal| identifiers will appear in the \PASCAL\ program as
  719. ordinary identifiers since they have not been defined to be macros; the
  720. corresponding value in the |equiv| array
  721. for such identifiers is a link in a secondary hash table that
  722. is used to check whether any two of them agree in their first |unambig_length|
  723. characters after underline symbols are removed and lowercase letters are
  724. changed to uppercase.
  725. \yskip\hang |numeric| identifiers have been defined to be numeric macros;
  726. their |equiv| value contains the corresponding numeric value plus $2^{15}$.
  727. Strings are treated as numeric macros.
  728. \yskip\hang |simple| identifiers have been defined to be simple macros;
  729. their |equiv| value points to the corresponding replacement text.
  730. \yskip\hang |parametric| identifiers have been defined to be parametric macros;
  731. like simple identifiers, their |equiv| value points to the replacement text.
  732. @d normal=0 {ordinary identifiers have |normal| ilk}
  733. @d numeric=1 {numeric macros and strings have |numeric| ilk}
  734. @d simple=2 {simple macros have |simple| ilk}
  735. @d parametric=3 {parametric macros have |parametric| ilk}
  736. @ The names of modules are stored in |byte_mem| together
  737. with the identifier names, but a hash table is not used for them because
  738. \.{TANGLE} needs to be able to recognize a module name when given a prefix of
  739. that name. A conventional binary seach tree is used to retrieve module names,
  740. with fields called |llink| and |rlink| in place of |link| and |ilk|. The
  741. root of this tree is |rlink[0]|. If |p| is a pointer to a module name,
  742. |equiv[p]| points to its replacement text, just as in simple and parametric
  743. macros, unless this replacement text has not yet been defined (in which case
  744. |equiv[p]=0|).
  745. @d llink==link {left link in binary search tree for module names}
  746. @d rlink==ilk {right link in binary search tree for module names}
  747. @<Set init...@>=
  748. rlink[0]:=0; {the binary search tree starts out with nothing in it}
  749. equiv[0]:=0; {the undefined module has no replacement text}
  750. @ Here is a little procedure that prints the text of a given name.
  751. @p procedure print_id(@!p:name_pointer); {print identifier or module name}
  752. var k:0..max_bytes; {index into |byte_mem|}
  753. @!w:0..ww-1; {segment of |byte_mem|}
  754. begin if p>=name_ptr then print('IMPOSSIBLE')
  755. else  begin w:=p mod ww;
  756.   for k:=byte_start[p] to byte_start[p+ww]-1 do print(xchr[byte_mem[w,k]]);
  757.   end;
  758. @* Searching for identifiers.
  759. The hash table described above is updated by the |id_lookup| procedure,
  760. which finds a given identifier and returns a pointer to its index in
  761. |byte_start|. If the identifier was not already present, it is inserted with
  762. a given |ilk| code; and an error message is printed if the identifier is being
  763. doubly defined.
  764. Because of the way \.{TANGLE}'s scanning mechanism works, it is most convenient
  765. to let |id_lookup| search for an identifier that is present in the |buffer|
  766. array. Two other global variables specify its position in the buffer: the
  767. first character is |buffer[id_first]|, and the last is |buffer[id_loc-1]|.
  768. Furthermore, if the identifier is really a string, the global variable
  769. |double_chars| tells how many of the characters in the buffer appear
  770. twice (namely \.{@@@@} and \.{""}), since this additional information makes
  771. it easy to calculate the true length of the string. The final double-quote
  772. of the string is not included in its ``identifier,'' but the first one is,
  773. so the string length is |id_loc-id_first-double_chars-1|.
  774. We have mentioned that |normal| identifiers belong to two hash tables,
  775. one for their true names as they appear in the \.{WEB} file and the other
  776. when they have been reduced to their first |unambig_length| characters.
  777. The hash tables are kept by the method of simple chaining, where the
  778. heads of the individual lists appear in the |hash| and |chop_hash| arrays.
  779. If |h| is a hash code, the primary hash table list starts at |hash[h]| and
  780. proceeds through |link| pointers; the secondary hash table list starts at
  781. |chop_hash[h]| and proceeds through |equiv| pointers. Of course, the same
  782. identifier will probably have two different values of |h|.
  783. The |id_lookup| procedure uses an auxiliary array called |chopped_id| to
  784. contain up to |unambig_length| characters of the current identifier, if
  785. it is necessary to compute the secondary hash code. (This array could be
  786. declared local to |id_lookup|, but in general we are making all array
  787. declarations global in this program, because some compilers and some machine
  788. architectures make dynamic array allocation inefficient.)
  789. @<Glob...@>=
  790. @!id_first:0..buf_size; {where the current identifier begins in the buffer}
  791. @!id_loc:0..buf_size; {just after the current identifier in the buffer}
  792. @!double_chars:0..buf_size; {correction to length in case of strings}
  793. @!hash,@!chop_hash:array [0..hash_size] of sixteen_bits; {heads of hash lists}
  794. @!chopped_id:array [0..unambig_length] of ASCII_code; {chopped identifier}
  795. @ Initially all the hash lists are empty.
  796. @<Local variables for init...@>=
  797. @!h:0..hash_size; {index into hash-head arrays}
  798. @ @<Set init...@>=
  799. for h:=0 to hash_size-1 do
  800.   begin hash[h]:=0; chop_hash[h]:=0;
  801.   end;
  802. @ Here now is the main procedure for finding identifiers (and strings).
  803. The parameter |t| is set to |normal| except when the identifier is
  804. a macro name that is just being defined; in the latter case, |t| will be
  805. |numeric|, |simple|, or |parametric|.
  806. @p function id_lookup(@!t:eight_bits):name_pointer; {finds current identifier}
  807. label found, not_found;
  808. var c:eight_bits; {byte being chopped}
  809. @!i:0..buf_size; {index into |buffer|}
  810. @!h:0..hash_size; {hash code}
  811. @!k:0..max_bytes; {index into |byte_mem|}
  812. @!w:0..ww-1; {segment of |byte_mem|}
  813. @!l:0..buf_size; {length of the given identifier}
  814. @!p,@!q:name_pointer; {where the identifier is being sought}
  815. @!s:0..unambig_length; {index into |chopped_id|}
  816. begin l:=id_loc-id_first; {compute the length}
  817. @<Compute the hash code |h|@>;
  818. @<Compute the name location |p|@>;
  819. if (p=name_ptr)or(t<>normal) then
  820.   @<Update the tables and check for possible errors@>;
  821. id_lookup:=p;
  822. @ A simple hash code is used: If the sequence of
  823. ASCII codes is $c_1c_2\ldots c_m$, its hash value will be
  824. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  825. @<Compute the hash...@>=
  826. h:=buffer[id_first]; i:=id_first+1;
  827. while i<id_loc do
  828.   begin h:=(h+h+buffer[i]) mod hash_size; incr(i);
  829.   end
  830. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  831. otherwise |p| will point to its existing location.
  832. @<Compute the name location...@>=
  833. p:=hash[h];
  834. while p<>0 do
  835.   begin if length(p)=l then
  836.       @<Compare name |p| with current identifier, |goto found| if equal@>;
  837.   p:=link[p];
  838.   end;
  839. p:=name_ptr; {the current identifier is new}
  840. link[p]:=hash[h]; hash[h]:=p; {insert |p| at beginning of hash list}
  841. found:
  842. @ @<Compare name |p|...@>=
  843. begin i:=id_first; k:=byte_start[p]; w:=p mod ww;
  844. while (i<id_loc)and(buffer[i]=byte_mem[w,k]) do
  845.   begin incr(i); incr(k);
  846.   end;
  847. if i=id_loc then goto found; {all characters agree}
  848. @ @<Update the tables...@>=
  849. begin if ((p<>name_ptr)and(t<>normal)and(ilk[p]=normal)) or
  850.     ((p=name_ptr)and(t=normal)and(buffer[id_first]<>"""")) then
  851.   @<Compute the secondary hash code |h| and put the first characters
  852.   into the auxiliary array |chopped_id|@>;
  853. if p<>name_ptr then
  854.   @<Give double-definition error, if necessary, and change |p| to type |t|@>
  855. else @<Enter a new identifier into the table at position |p|@>;
  856. @ The following routine, which is called into play when it is necessary to
  857. look at the secondary hash table, computes the same hash function as before
  858. (but on the chopped data), and places a zero after the chopped identifier
  859. in |chopped_id| to serve as a convenient sentinel.
  860. @<Compute the secondary...@>=
  861. begin i:=id_first; s:=0; h:=0;
  862. while (i<id_loc)and(s<unambig_length) do
  863.   begin if buffer[i]<>"_" then
  864.     begin if buffer[i]>="a" then chopped_id[s]:=buffer[i]-@'40
  865.     else chopped_id[s]:=buffer[i];
  866.     h:=(h+h+chopped_id[s]) mod hash_size; incr(s);
  867.     end;
  868.   incr(i);
  869.   end;
  870. chopped_id[s]:=0;
  871. @ If a nonnumeric macro has appeared before it was defined, \.{TANGLE}
  872. will still work all right; after all, such behavior is typical of the
  873. replacement texts for modules, which act very much like macros.
  874. However, an undefined numeric macro may not be used on the right-hand
  875. side of another numeric macro definition, so \.{TANGLE} finds it
  876. simplest to make a blanket rule that numeric macros should be defined
  877. before they are used. The following routine gives an error message and
  878. also fixes up any damage that may have been caused.
  879. @<Give double...@>= {now |p<>name_ptr| and |t<>normal|}
  880. begin if ilk[p]=normal then
  881.   begin if t=numeric then err_print('! This identifier has already appeared');
  882. @.This identifier has already...@>
  883.   @<Remove |p| from secondary hash table@>;
  884.   end
  885. else err_print('! This identifier was defined before');
  886. @.This identifier was defined...@>
  887. ilk[p]:=t;
  888. @ When we have to remove a secondary hash entry, because a |normal| identifier
  889. is changing to another |ilk|, the hash code |h| and chopped identifier have
  890. already been computed.
  891. @<Remove |p| from secondary...@>=
  892. q:=chop_hash[h];
  893. if q=p then chop_hash[h]:=equiv[p]
  894. else  begin while equiv[q]<>p do q:=equiv[q];
  895.   equiv[q]:=equiv[p];
  896.   end
  897. @ The following routine could make good use of a generalized |pack| procedure
  898. that puts items into just part of a packed array instead of the whole thing.
  899. @<Enter a new identifier...@>=
  900. begin if (t=normal)and(buffer[id_first]<>"""") then
  901.   @<Check for ambiguity and update secondary hash@>;
  902. w:=name_ptr mod ww; k:=byte_ptr[w];
  903. if k+l>max_bytes then overflow('byte memory');
  904. if name_ptr>max_names-ww then overflow('name');
  905. i:=id_first; {get ready to move the identifier into |byte_mem|}
  906. while i<id_loc do
  907.   begin byte_mem[w,k]:=buffer[i]; incr(k); incr(i);
  908.   end;
  909. byte_ptr[w]:=k; byte_start[name_ptr+ww]:=k; incr(name_ptr);
  910. if buffer[id_first]<>"""" then ilk[p]:=t
  911. else @<Define and output a new string of the pool@>;
  912. @ @<Check for ambig...@>=
  913. begin q:=chop_hash[h];
  914. while q<>0 do
  915.   begin @<Check if |q| conflicts with |p|@>;
  916.   q:=equiv[q];
  917.   end;
  918. equiv[p]:=chop_hash[h]; chop_hash[h]:=p; {put |p| at front of secondary list}
  919. @ @<Check if |q| conflicts...@>=
  920. begin k:=byte_start[q]; s:=0; w:=q mod ww;
  921. while (k<byte_start[q+ww]) and (s<unambig_length) do
  922.   begin c:=byte_mem[w,k];
  923.   if c<>"_" then
  924.     begin if c>="a" then c:=c-@'40; {merge lowercase with uppercase}
  925.     if chopped_id[s]<>c then goto not_found;
  926.     incr(s);
  927.     end;
  928.   incr(k);
  929.   end;
  930. if (k=byte_start[q+ww])and(chopped_id[s]<>0) then goto not_found;
  931. print_nl('! Identifier conflict with ');
  932. @.Identifier conflict...@>
  933. for k:=byte_start[q] to byte_start[q+ww]-1 do print(xchr[byte_mem[w,k]]);
  934. error; q:=0; {only one conflict will be printed, since |equiv[0]=0|}
  935. not_found:
  936. @ We compute the string pool check sum by working modulo a prime number
  937. that is large but not so large that overflow might occur.
  938. @d check_sum_prime==@'3777777667 {$2^{29}-73$}
  939. @^preprocessed strings@>
  940. @<Define and output a new string...@>=
  941. begin ilk[p]:=numeric; {strings are like numeric macros}
  942. if l-double_chars=2 then {this string is for a single character}
  943.   equiv[p]:=buffer[id_first+1]+@'100000
  944. else  begin equiv[p]:=string_ptr+@'100000;
  945.   l:=l-double_chars-1;
  946.   if l>99 then err_print('! Preprocessed string is too long');
  947. @.Preprocessed string is too long@>
  948.   incr(string_ptr);
  949.   write(pool,xchr["0"+l div 10],xchr["0"+l mod 10]); {output the length}
  950.   pool_check_sum:=pool_check_sum+pool_check_sum+l;
  951.   while pool_check_sum>check_sum_prime do
  952.     pool_check_sum:=pool_check_sum-check_sum_prime;
  953.   i:=id_first+1;
  954.   while i<id_loc do
  955.     begin write(pool,xchr[buffer[i]]); {output characters of string}
  956.     pool_check_sum:=pool_check_sum+pool_check_sum+buffer[i];
  957.     while pool_check_sum>check_sum_prime do
  958.       pool_check_sum:=pool_check_sum-check_sum_prime;
  959.     if (buffer[i]="""") or (buffer[i]="@@") then
  960.       i:=i+2 {omit second appearance of doubled character}
  961.     else incr(i);
  962.     end;
  963.   write_ln(pool);
  964.   end;
  965. @* Searching for module names.
  966. The |mod_lookup| procedure finds the module name |mod_text[1..l]| in the
  967. search tree, after inserting it if necessary, and returns a pointer to
  968. where it was found.
  969. @<Glob...@>=
  970. @!mod_text:array [0..longest_name] of ASCII_code; {name being sought for}
  971. @ According to the rules of \.{WEB}, no module name
  972. should be a proper prefix of another, so a ``clean'' comparison should
  973. occur between any two names. The result of |mod_lookup| is 0 if this
  974. prefix condition is violated. An error message is printed when such violations
  975. are detected during phase two of \.{WEAVE}.
  976. @d less=0 {the first name is lexicographically less than the second}
  977. @d equal=1 {the first name is equal to the second}
  978. @d greater=2 {the first name is lexicographically greater than the second}
  979. @d prefix=3 {the first name is a proper prefix of the second}
  980. @d extension=4 {the first name is a proper extension of the second}
  981. @p function mod_lookup(@!l:sixteen_bits):name_pointer; {finds module name}
  982. label found;
  983. var c:less..extension; {comparison between two names}
  984. @!j:0..longest_name; {index into |mod_text|}
  985. @!k:0..max_bytes; {index into |byte_mem|}
  986. @!w:0..ww-1; {segment of |byte_mem|}
  987. @!p:name_pointer; {current node of the search tree}
  988. @!q:name_pointer; {father of node |p|}
  989. begin c:=greater; q:=0; p:=rlink[0]; {|rlink[0]| is the root of the tree}
  990. while p<>0 do
  991.   begin @<Set \(|c| to the result of comparing the given name to
  992.     name |p|@>;
  993.   q:=p;
  994.   if c=less then p:=llink[q]
  995.   else if c=greater then p:=rlink[q]
  996.   else goto found;
  997.   end;
  998. @<Enter a new module name into the tree@>;
  999. found: if c<>equal then
  1000.   begin err_print('! Incompatible section names'); p:=0;
  1001. @.Incompatible module names@>
  1002.   end;
  1003. mod_lookup:=p;
  1004. @ @<Enter a new module name...@>=
  1005. w:=name_ptr mod ww; k:=byte_ptr[w];
  1006. if k+l>max_bytes then overflow('byte memory');
  1007. if name_ptr>max_names-ww then overflow('name');
  1008. p:=name_ptr;
  1009. if c=less then llink[q]:=p else rlink[q]:=p;
  1010. llink[p]:=0; rlink[p]:=0; c:=equal; equiv[p]:=0;
  1011. for j:=1 to l do byte_mem[w,k+j-1]:=mod_text[j];
  1012. byte_ptr[w]:=k+l; byte_start[name_ptr+ww]:=k+l; incr(name_ptr);
  1013. @ @<Set \(|c|...@>=
  1014. begin k:=byte_start[p]; w:=p mod ww; c:=equal; j:=1;
  1015. while (k<byte_start[p+ww]) and (j<=l) and (mod_text[j]=byte_mem[w,k]) do
  1016.   begin incr(k); incr(j);
  1017.   end;
  1018. if k=byte_start[p+ww] then
  1019.   if j>l then c:=equal
  1020.   else c:=extension
  1021. else if j>l then c:=prefix
  1022. else if mod_text[j]<byte_mem[w,k] then c:=less
  1023. else c:=greater;
  1024. @ The |prefix_lookup| procedure is supposed to find exactly one module
  1025. name that has |mod_text[1..l]| as a prefix. Actually the algorithm silently
  1026. accepts also the situation that some module name is a prefix of
  1027. |mod_text[1..l]|, because the user who painstakingly typed in more than
  1028. necessary probably doesn't want to be told about the wasted effort.
  1029. @p function prefix_lookup(@!l:sixteen_bits):name_pointer; {finds name extension}
  1030. var c:less..extension; {comparison between two names}
  1031. @!count:0..max_names; {the number of hits}
  1032. @!j:0..longest_name; {index into |mod_text|}
  1033. @!k:0..max_bytes; {index into |byte_mem|}
  1034. @!w:0..ww-1; {segment of |byte_mem|}
  1035. @!p:name_pointer; {current node of the search tree}
  1036. @!q:name_pointer; {another place to resume the search after one branch is done}
  1037. @!r:name_pointer; {extension found}
  1038. begin q:=0; p:=rlink[0]; count:=0; r:=0; {begin search at root of tree}
  1039. while p<>0 do
  1040.   begin @<Set \(|c|...@>;
  1041.   if c=less then p:=llink[p]
  1042.   else if c=greater then p:=rlink[p]
  1043.   else  begin r:=p; incr(count); q:=rlink[p]; p:=llink[p];
  1044.     end;
  1045.   if p=0 then
  1046.     begin p:=q; q:=0;
  1047.     end;
  1048.   end;
  1049. if count<>1 then
  1050.   if count=0 then err_print('! Name does not match')
  1051. @.Name does not match@>
  1052.   else err_print('! Ambiguous prefix');
  1053. @.Ambiguous prefix@>
  1054. prefix_lookup:=r; {the result will be 0 if there was no match}
  1055. @* Tokens.
  1056. Replacement texts, which represent \PASCAL\ code in a compressed format,
  1057. appear in |tok_mem| as mentioned above. The codes in
  1058. these texts are called `tokens'; some tokens occupy two consecutive
  1059. eight-bit byte positions, and the others take just one byte.
  1060. If $p>0$ points to a replacement text, |tok_start[p]| is the |tok_mem| position
  1061. of the first eight-bit code of that text. If |text_link[p]=0|,
  1062. this is the replacement text for a macro, otherwise it is the replacement
  1063. text for a module. In the latter case |text_link[p]| is either equal to
  1064. |module_flag|, which means that there is no further text for this module, or
  1065. |text_link[p]| points to a
  1066. continuation of this replacement text; such links are created when
  1067. several modules have \PASCAL\ texts with the same name, and they also
  1068. tie together all the \PASCAL\ texts of unnamed modules.
  1069. The replacement text pointer for the first unnamed module
  1070. appears in |text_link[0]|, and the most recent such pointer is |last_unnamed|.
  1071. @d module_flag==max_texts {final |text_link| in module replacement texts}
  1072. @<Glob...@>=
  1073. @!last_unnamed:text_pointer; {most recent replacement text of unnamed module}
  1074. @ @<Set init...@>= last_unnamed:=0; text_link[0]:=0;
  1075. @ If the first byte of a token is less than @'200, the token occupies a
  1076. single byte. Otherwise we make a sixteen-bit token by combining two consecutive
  1077. bytes |a| and |b|. If |@'200<=a<@'250|, then $(a-@'200)\times2^8+b$ points
  1078. to an identifier; if |@'250<=a<@'320|, then
  1079. $(a-@'250)\times2^8+b$ points to a module name; otherwise, i.e., if
  1080. |@'320<=a<@'400|, then $(a-@'320)\times2^8+b$ is the number of the module
  1081. in which the current replacement text appears.
  1082. Codes less than @'200 are 7-bit ASCII codes that represent themselves.
  1083. In particular, a single-character identifier like `|x|' will be a one-byte
  1084. token, while all longer identifiers will occupy two bytes.
  1085. Some of the 7-bit ASCII codes will not be present, however, so we can
  1086. use them for special purposes. The following symbolic names are used:
  1087. \yskip\hang |param| denotes insertion of a parameter. This occurs only in
  1088. the replacement texts of parametric macros, outside of single-quoted strings
  1089. in those texts.
  1090. \hang |begin_comment| denotes \.{@@\{}, which will become either
  1091. \.{\{} or \.{[}.
  1092. \hang |end_comment| denotes \.{@@\}}, which will become either
  1093. \.{\}} or \.{]}.
  1094. \hang |octal| denotes the \.{@@\'} that precedes an octal constant.
  1095. \hang |hex| denotes the \.{@@"} that precedes a hexadecimal constant.
  1096. \hang |check_sum| denotes the \.{@@\char'44} that denotes the string pool
  1097. check sum.
  1098. \hang |join| denotes the concatenation of adjacent items with no
  1099. space or line breaks allowed between them (the \.{@@\&} operation of \.{WEB}).
  1100. \hang |double_dot| denotes `\.{..}' in \PASCAL.
  1101. \hang |verbatim| denotes the \.{@@=} that begins a verbatim \PASCAL\ string.
  1102. It is also used for the end of the string.
  1103. \hang |force_line| denotes the \.{@@\\} that forces a new line in the
  1104. \PASCAL\ output.
  1105. @^ASCII code@>
  1106. @d param=0 {ASCII null code will not appear}
  1107. @d verbatim=@'2 {extended ASCII alpha should not appear}
  1108. @d force_line=@'3 {extended ASCII beta should not appear}
  1109. @d begin_comment=@'11 {ASCII tab mark will not appear}
  1110. @d end_comment=@'12 {ASCII line feed will not appear}
  1111. @d octal=@'14 {ASCII form feed will not appear}
  1112. @d hex=@'15 {ASCII carriage return will not appear}
  1113. @d double_dot=@'40 {ASCII space will not appear except in strings}
  1114. @d check_sum=@'175 {will not be confused with right brace}
  1115. @d join=@'177 {ASCII delete will not appear}
  1116. @ The following procedure is used to enter a two-byte value into
  1117. |tok_mem| when a replacement text is being generated.
  1118. @p procedure store_two_bytes(@!x:sixteen_bits);
  1119.   {stores high byte, then low byte}
  1120. begin if tok_ptr[z]+2>max_toks then overflow('token');
  1121. tok_mem[z,tok_ptr[z]]:=x div@'400; {this could be done by a shift command}
  1122. tok_mem[z,tok_ptr[z]+1]:=x mod@'400; {this could be done by a logical and}
  1123. tok_ptr[z]:=tok_ptr[z]+2;
  1124. @ When \.{TANGLE} is being operated in debug mode, it has a procedure to display
  1125. a replacement text in symbolic form. This procedure has not been spruced up to
  1126. generate a real great format, but at least the results are not as bad as
  1127. a memory dump.
  1128. @p @!debug procedure print_repl(@!p:text_pointer);
  1129. var k:0..max_toks; {index into |tok_mem|}
  1130. @!a: sixteen_bits; {current byte(s)}
  1131. @!zp: 0..zz-1; {segment of |tok_mem| being accessed}
  1132. begin if p>=text_ptr then print('BAD')
  1133. else  begin k:=tok_start[p]; zp:=p mod zz;
  1134.   while k<tok_start[p+zz] do
  1135.     begin a:=tok_mem[zp,k];
  1136.     if a>=@'200 then @<Display two-byte token starting with |a|@>
  1137.     else @<Display one-byte token |a|@>;
  1138.     incr(k);
  1139.     end;
  1140.   end;
  1141. gubed
  1142. @ @<Display two-byte...@>=
  1143. begin incr(k);
  1144. if a<@'250 then {identifier or string}
  1145.   begin a:=(a-@'200)*@'400+tok_mem[zp,k]; print_id(a);
  1146.   if byte_mem[a mod ww,byte_start[a]]="""" then print('"')
  1147.   else print(' ');
  1148.   end
  1149. else if a<@'320 then {module name}
  1150.   begin print('@@<'); print_id((a-@'250)*@'400+tok_mem[zp,k]);
  1151.   print('@@>');
  1152.   end
  1153. else  begin a:=(a-@'320)*@'400+tok_mem[zp,k]; {module number}
  1154.   print('@@',xchr["{"],a:1,'@@',xchr["}"]); {can't use right brace
  1155.     between \&{debug} and \&{gubed}}
  1156.   end;
  1157. @ @<Display one-byte...@>=
  1158. case a of
  1159. begin_comment: print('@@',xchr["{"]);
  1160. end_comment: print('@@',xchr["}"]); {can't use right brace
  1161.     between \&{debug} and \&{gubed}}
  1162. octal: print('@@''');
  1163. hex: print('@@"');
  1164. check_sum: print('@@$');
  1165. param: print('#');
  1166. "@@": print('@@@@');
  1167. verbatim: print('@@=');
  1168. force_line: print('@@\');
  1169. othercases print(xchr[a])
  1170. endcases
  1171. @* Stacks for output.
  1172. Let's make sure that our data structures contain enough information to
  1173. produce the entire \PASCAL\ program as desired, by working next on the
  1174. algorithms that actually do produce that program.
  1175. @ The output process uses a stack to keep track of what is going on at
  1176. different ``levels'' as the macros are being expanded.
  1177. Entries on this stack have five parts:
  1178. \yskip\hang |end_field| is the |tok_mem| location where the replacement
  1179. text of a particular level will end;
  1180. \hang |byte_field| is the |tok_mem| location from which the next token
  1181. on a particular level will be read;
  1182. \hang |name_field| points to the name corresponding to a particular level;
  1183. \hang |repl_field| points to the replacement text currently being read
  1184. at a particular level.
  1185. \hang |mod_field| is the module number, or zero if this is a macro.
  1186. \yskip\noindent The current values of these five quantities are referred to
  1187. quite frequently, so they are stored in a separate place instead of in
  1188. the |stack| array. We call the current values |cur_end|, |cur_byte|,
  1189. |cur_name|, |cur_repl|, and |cur_mod|.
  1190. The global variable |stack_ptr| tells how many levels of output are
  1191. currently in progress. The end of all output occurs when the stack is
  1192. empty, i.e., when |stack_ptr=0|.
  1193. @<Types...@>=
  1194. @t\4@>@!output_state=record
  1195.   @!end_field: sixteen_bits; {ending location of replacement text}
  1196.   @!byte_field: sixteen_bits; {present location within replacement text}
  1197.   @!name_field: name_pointer; {|byte_start| index for text being output}
  1198.   @!repl_field: text_pointer; {|tok_start| index for text being output}
  1199.   @!mod_field: 0..@'27777; {module number or zero if not a module}
  1200.   end;
  1201. @ @d cur_end==cur_state.end_field {current ending location in |tok_mem|}
  1202. @d cur_byte==cur_state.byte_field {location of next output byte in |tok_mem|}
  1203. @d cur_name==cur_state.name_field {pointer to current name being expanded}
  1204. @d cur_repl==cur_state.repl_field {pointer to current replacement text}
  1205. @d cur_mod==cur_state.mod_field {current module number being expanded}
  1206. @<Globals...@>=
  1207. @!cur_state : output_state; {|cur_end|, |cur_byte|, |cur_name|, |cur_repl|}
  1208. @!stack : array [1..stack_size] of output_state; {info for non-current levels}
  1209. @!stack_ptr: 0..stack_size; {first unused location in the output state stack}
  1210. @ It is convenient to keep a global variable |zo| equal to |cur_repl mod zz|.
  1211. @<Glob...@>=
  1212. @!zo:0..zz-1; {the segment of |tok_mem| from which output is coming}
  1213. @ Parameters must also be stacked. They are placed in
  1214. |tok_mem| just above the other replacement texts, and dummy parameter
  1215. `names' are placed in |byte_start| just after the other names.
  1216. The variables |text_ptr| and |tok_ptr[z]| essentially serve as parameter
  1217. stack pointers during the output phase, so there is no need for a separate
  1218. data structure to handle this problem.
  1219. @ There is an implicit stack corresponding to meta-comments that are output
  1220. via \.{@@\{} and \.{@@\}}. But this stack need not be represented in detail,
  1221. because we only need to know whether it is empty or not. A global variable
  1222. |brace_level| tells how many items would be on this stack if it were present.
  1223. @<Globals...@>=
  1224. @!brace_level: eight_bits; {current depth of $\.{@@\{}\ldots\.{@@\}}$ nesting}
  1225. @ To get the output process started, we will perform the following
  1226. initialization steps. We may assume that |text_link[0]| is nonzero, since it
  1227. points to the \PASCAL\ text in the first unnamed module that generates
  1228. code; if there are no such modules, there is nothing to output, and an
  1229. error message will have been generated before we do any of the initialization.
  1230. @<Initialize the output stacks@>=
  1231. stack_ptr:=1; brace_level:=0; cur_name:=0; cur_repl:=text_link[0];
  1232. zo:=cur_repl mod zz; cur_byte:=tok_start[cur_repl];
  1233. cur_end:=tok_start[cur_repl+zz]; cur_mod:=0;
  1234. @ When the replacement text for name |p| is to be inserted into the output,
  1235. the following subroutine is called to save the old level of output and get
  1236. the new one going.
  1237. @p procedure push_level(@!p:name_pointer); {suspends the current level}
  1238. begin if stack_ptr=stack_size then overflow('stack')
  1239. else  begin stack[stack_ptr]:=cur_state; {save |cur_end|, |cur_byte|, etc.}
  1240.   incr(stack_ptr);
  1241.   cur_name:=p; cur_repl:=equiv[p]; zo:=cur_repl mod zz;
  1242.   cur_byte:=tok_start[cur_repl]; cur_end:=tok_start[cur_repl+zz];
  1243.   cur_mod:=0;
  1244.   end;
  1245. @ When we come to the end of a replacement text, the |pop_level| subroutine
  1246. does the right thing: It either moves to the continuation of this replacement
  1247. text or returns the state to the most recently stacked level. Part of this
  1248. subroutine, which updates the parameter stack, will be given later when we
  1249. study the parameter stack in more detail.
  1250. @p procedure pop_level; {do this when |cur_byte| reaches |cur_end|}
  1251. label exit;
  1252. begin if text_link[cur_repl]=0 then {end of macro expansion}
  1253.   begin if ilk[cur_name]=parametric then
  1254.     @<Remove a parameter from the parameter stack@>;
  1255.   end
  1256. else if text_link[cur_repl]<module_flag then {link to a continuation}
  1257.   begin cur_repl:=text_link[cur_repl]; {we will stay on the same level}
  1258.   zo:=cur_repl mod zz;
  1259.   cur_byte:=tok_start[cur_repl]; cur_end:=tok_start[cur_repl+zz];
  1260.   return;
  1261.   end;
  1262. decr(stack_ptr); {we will go down to the previous level}
  1263. if stack_ptr>0 then
  1264.   begin cur_state:=stack[stack_ptr]; zo:=cur_repl mod zz;
  1265.   end;
  1266. exit: end;
  1267. @ The heart of the output procedure is the |get_output| routine, which produces
  1268. the next token of output that is not a reference to a macro. This procedure
  1269. handles all the stacking and unstacking that is necessary. It returns the
  1270. value |number| if the next output has a numeric value (the value of a
  1271. numeric macro or string), in which case |cur_val| has been set to the
  1272. number in question. The procedure also returns the value |module_number|
  1273. if the next output begins or ends the replacement text of some module,
  1274. in which case |cur_val| is that module's number (if beginning) or the
  1275. negative of that value (if ending). And it returns the value |identifier|
  1276. if the next output is an identifier of length two or more, in which case
  1277. |cur_val| points to that identifier name.
  1278. @d number=@'200 {code returned by |get_output| when next output is numeric}
  1279. @d module_number=@'201 {code returned by |get_output| for module numbers}
  1280. @d identifier=@'202 {code returned by |get_output| for identifiers}
  1281. @<Globals...@>=
  1282. @!cur_val:integer; {additional information corresponding to output token}
  1283. @ If |get_output| finds that no more output remains, it returns the value zero.
  1284. @p function get_output:sixteen_bits; {returns next token after macro expansion}
  1285. label restart, done, found;
  1286. var a:sixteen_bits; {value of current byte}
  1287. @!b:eight_bits; {byte being copied}
  1288. @!bal:sixteen_bits; {excess of \.( versus \.) while copying a parameter}
  1289. @!k:0..max_bytes; {index into |byte_mem|}
  1290. @!w:0..ww-1; {segment of |byte_mem|}
  1291. begin restart: if stack_ptr=0 then
  1292.   begin a:=0; goto found;
  1293.   end;
  1294. if cur_byte=cur_end then
  1295.   begin cur_val:=-cur_mod; pop_level;
  1296.   if cur_val=0 then goto restart;
  1297.   a:=module_number; goto found;
  1298.   end;
  1299. a:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1300. if a<@'200 then {one-byte token}
  1301.   if a=param then
  1302.       @<Start scanning current macro parameter, |goto restart|@>
  1303.   else goto found;
  1304. a:=(a-@'200)*@'400+tok_mem[zo,cur_byte]; incr(cur_byte);
  1305. if a<@'24000 then {|@'24000=(@'250-@'200)*@'400|}
  1306.   @<Expand macro |a| and |goto found|, or |goto restart| if no output found@>;
  1307. if a<@'50000 then {|@'50000=(@'320-@'200)*@'400|}
  1308.   @<Expand module |a-@'24000|, |goto restart|@>;
  1309. cur_val:=a-@'50000; a:=module_number; cur_mod:=cur_val;
  1310. found:
  1311. @!debug if trouble_shooting then debug_help;@;@+gubed@/
  1312. get_output:=a;
  1313. @ The user may have forgotten to give any \PASCAL\ text for a module name,
  1314. or the \PASCAL\ text may have been associated with a different name by mistake.
  1315. @<Expand module |a-...@>=
  1316. begin a:=a-@'24000;
  1317. if equiv[a]<>0 then push_level(a)
  1318. else if a<>0 then
  1319.   begin print_nl('! Not present: <'); print_id(a); print('>'); error;
  1320. @.Not present: <section name>@>
  1321.   end;
  1322. goto restart;
  1323. @ @<Expand macro ...@>=
  1324. begin case ilk[a] of
  1325. normal: begin cur_val:=a; a:=identifier;
  1326.   end;
  1327. numeric: begin cur_val:=equiv[a]-@'100000; a:=number;
  1328.   end;
  1329. simple: begin push_level(a); goto restart;
  1330.   end;
  1331. parametric: begin @<Put a parameter on the parameter stack,
  1332.   or |goto restart| if error occurs@>;
  1333.   push_level(a); goto restart;
  1334.   end;
  1335. othercases confusion('output')
  1336. endcases;@/
  1337. goto found;
  1338. @ We come now to the interesting part, the job of putting a parameter on
  1339. the parameter stack. First we pop the stack if necessary until getting to
  1340. a level that hasn't ended. Then the next character must be a `\.(';
  1341. and since parentheses are balanced on each level, the entire parameter must
  1342. be present, so we can copy it without difficulty.
  1343. @<Put a parameter...@>=
  1344. while (cur_byte=cur_end)and(stack_ptr>0) do pop_level;
  1345. if (stack_ptr=0)or(tok_mem[zo,cur_byte]<>"(") then
  1346.   begin print_nl('! No parameter given for '); print_id(a); error;
  1347. @.No parameter given for macro@>
  1348.   goto restart;
  1349.   end;
  1350. @<Copy the parameter into |tok_mem|@>;
  1351. equiv[name_ptr]:=text_ptr; ilk[name_ptr]:=simple; w:=name_ptr mod ww;
  1352. k:=byte_ptr[w];
  1353. @!debug if k=max_bytes then overflow('byte memory');
  1354. byte_mem[w,k]:="#"; incr(k); byte_ptr[w]:=k;
  1355. gubed {this code has set the parameter identifier for debugging printouts}
  1356. if name_ptr>max_names-ww then overflow('name');
  1357. byte_start[name_ptr+ww]:=k; incr(name_ptr);
  1358. if text_ptr>max_texts-zz then overflow('text');
  1359. text_link[text_ptr]:=0; tok_start[text_ptr+zz]:=tok_ptr[z];
  1360. incr(text_ptr);
  1361. z:=text_ptr mod zz
  1362. @ The |pop_level| routine undoes the effect of parameter-pushing when
  1363. a parameter macro is finished:
  1364. @<Remove a parameter...@>=
  1365. begin decr(name_ptr); decr(text_ptr);
  1366. z:=text_ptr mod zz;
  1367. stat if tok_ptr[z]>max_tok_ptr[z] then max_tok_ptr[z]:=tok_ptr[z];
  1368. tats {the maximum value of |tok_ptr| occurs just before parameter popping}
  1369. tok_ptr[z]:=tok_start[text_ptr];
  1370. @!debug decr(byte_ptr[name_ptr mod ww]);@+gubed
  1371. @ When a parameter occurs in a replacement text, we treat it as a simple
  1372. macro in position (|name_ptr-1|):
  1373. @<Start scanning...@>=
  1374. begin push_level(name_ptr-1); goto restart;
  1375. @ Similarly, a |param| token encountered as we copy a parameter is converted
  1376. into a simple macro call for |name_ptr-1|.
  1377. Some care is needed to handle cases like \\{macro}|(#; print('#)'))|; the
  1378. \.{\#} token will have been changed to |param| outside of strings, but we
  1379. still must distinguish `real' parentheses from those in strings.
  1380. @d app_repl(#)==begin if tok_ptr[z]=max_toks then overflow('token');
  1381.   tok_mem[z,tok_ptr[z]]:=#; incr(tok_ptr[z]); end
  1382. @<Copy the parameter...@>=
  1383. bal:=1; incr(cur_byte); {skip the opening `\.('}
  1384. loop@+  begin b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1385.   if b=param then store_two_bytes(name_ptr+@'77777)
  1386.   else  begin if b>=@'200 then
  1387.       begin app_repl(b);
  1388.       b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1389.       end
  1390.     else   case b of
  1391.       "(": incr(bal);
  1392.       ")":  begin decr(bal);
  1393.         if bal=0 then goto done;
  1394.         end;
  1395.       "'": repeat app_repl(b);
  1396.         b:=tok_mem[zo,cur_byte]; incr(cur_byte);
  1397.         until b="'"; {copy string, don't change |bal|}
  1398.       othercases do_nothing
  1399.       endcases;
  1400.     app_repl(b);
  1401.     end;
  1402.   end;
  1403. done:
  1404. @* Producing the output.
  1405. The |get_output| routine above handles most of the complexity of output
  1406. generation, but there are two further considerations that have a nontrivial
  1407. effect on \.{TANGLE}'s algorithms.
  1408. First, we want to make sure that the output is broken into lines not
  1409. exceeding |line_length| characters per line, where these breaks occur at
  1410. valid places (e.g., not in the middle of a string or a constant or an
  1411. identifier, not between `\.<' and `\.>', not at a `\.{@@\&}' position
  1412. where quantities are being joined together). Therefore we assemble the
  1413. output into a buffer before deciding where the line breaks will appear.
  1414. However, we make very little attempt to make ``logical'' line breaks that
  1415. would enhance the readability of the output; people are supposed to read
  1416. the input of \.{TANGLE} or the \TeX ed output of \.{WEAVE}, but not the
  1417. tangled-up output. The only concession to readability is that a break after
  1418. a semicolon will be made if possible, since commonly used ``pretty
  1419. printing'' routines give better results in such cases.
  1420. Second, we want to decimalize non-decimal constants, and to combine integer
  1421. quantities that are added or subtracted, because \PASCAL\ doesn't allow
  1422. constant expressions in subrange types or in case labels. This means we
  1423. want to have a procedure that treats a construction like \.{(E-15+17)}
  1424. as equivalent to `\.{(E+2)}', while also leaving `\.{(1E-15+17)}' and
  1425. `\.{(E-15+17*y)}' untouched. Consider also `\.{-15+17.5}' versus
  1426. `\.{-15+17..5}'. We shall not combine integers preceding or following
  1427. \.*, \./, \.{div}, \.{mod}, or \.{@@\&}. Note that if |y| has been defined
  1428. to equal $-2$, we must expand `\.{x*y}' into `\.{x*(-2)}'; but `\.{x-y}'
  1429. can expand into `\.{x+2}' and we can even change `\.{x - y mod z}' to
  1430. @^mod@>
  1431. `\.{x + 2 mod z}' because \PASCAL\ has a nonstandard \&{mod} operation!
  1432. The following solution to these problems has been adopted: An array
  1433. |out_buf| contains characters that have been generated but not yet output,
  1434. and there are three pointers into this array. One of these, |out_ptr|, is
  1435. the number of characters currently in the buffer, and we will have
  1436. |1<=out_ptr<=line_length| most of the time. The second is |break_ptr|,
  1437. which is the largest value |<=out_ptr| such that we are definitely entitled
  1438. to end a line by outputting the characters |out_buf[1..(break_ptr-1)]|;
  1439. we will always have |break_ptr<=line_length|. Finally, |semi_ptr| is either
  1440. zero or the largest known value of a legal break after a semicolon or comment
  1441. on the current line; we will always have |semi_ptr<=break_ptr|.
  1442. @<Globals...@>=
  1443. @!out_buf: array [0..out_buf_size] of ASCII_code; {assembled characters}
  1444. @!out_ptr: 0..out_buf_size; {first available place in |out_buf|}
  1445. @!break_ptr: 0..out_buf_size; {last breaking place in |out_buf|}
  1446. @!semi_ptr: 0..out_buf_size; {last semicolon breaking place in |out_buf|}
  1447. @ Besides having those three pointers,
  1448. the output process is in one of several states:
  1449. \yskip\hang |num_or_id| means that the last item in the buffer is a number or
  1450. identifier, hence a blank space or line break must be inserted if the next
  1451. item is also a number or identifier.
  1452. \yskip\hang |unbreakable| means that the last item in the buffer was followed
  1453. by the \.{@@\&} operation that inhibits spaces between it and the next item.
  1454. \yskip\hang |sign| means that the last item in the buffer is to be followed
  1455. by \.+ or \.-, depending on whether |out_app| is positive or negative.
  1456. \yskip\hang |sign_val| means that the decimal equivalent of
  1457. $\vert|out_val|\vert$ should be appended to the buffer. If |out_val<0|,
  1458. or if |out_val=0| and |last_sign<0|, the number should be preceded by a minus
  1459. sign. Otherwise it should be preceded by the character |out_sign| unless
  1460. |out_sign=0|; the |out_sign| variable is either 0 or \.{"\ "} or \.{"+"}.
  1461. \yskip\hang |sign_val_sign| is like |sign_val|, but also append \.+ or \.-
  1462. afterwards, depending on whether |out_app| is positive or negative.
  1463. \yskip\hang |sign_val_val| is like |sign_val|, but also append the decimal
  1464. equivalent of |out_app| including its sign, using |last_sign| in case
  1465. |out_app=0|.
  1466. \yskip\hang |misc| means none of the above.
  1467. \yskip\noindent
  1468. For example, the output buffer and output state run through the following
  1469. sequence as we generate characters from `\.{(x-15+19-2)}':
  1470. $$\vbox{\halign{$\hfil#\hfil$\quad&#\hfil&\quad\hfil#\hfil&\quad
  1471. \hfil#\hfil&\quad\hfil#\hfil&\quad\hfil#\hfil\quad&\hfil#\hfil\cr
  1472. output&|out_buf|&|out_state|&|out_sign|&|out_val|&|out_app|&|last_sign|\cr
  1473. \noalign{\vskip 3pt}
  1474. (&\.(&|misc|\cr
  1475. x&\.{(x}&|num_or_id|\cr
  1476. -&\.{(x}&|sign|&&&$-1$&$-1$\cr
  1477. 15&\.{(x}&|sign_val|&\.{"+"}&$-15$&&$-15$\cr
  1478. +&\.{(x}&|sign_val_sign|&\.{"+"}&$-15$&$+1$&$+1$\cr
  1479. 19&\.{(x}&|sign_val_val|&\.{"+"}&$-15$&$+19$&$+1$\cr
  1480. -&\.{(x}&|sign_val_sign|&\.{"+"}&$+4$&$-1$&$-1$\cr
  1481. 2&\.{(x}&|sign_val_val|&\.{"+"}&$+4$&$-2$&$-2$\cr
  1482. )&\.{(x+2)}&|misc|\cr}}$$
  1483. At each stage we have put as much into the buffer as possible without
  1484. knowing what is coming next. Examples like `\.{x-0.1}' indicate why
  1485. |last_sign| is needed to associate the proper sign with an output of zero.
  1486. In states |num_or_id|, |unbreakable|, and |misc| the last item in the buffer
  1487. lies between |break_ptr| and |out_ptr-1|, inclusive; in the other states we
  1488. have |break_ptr=out_ptr|.
  1489. The numeric values assigned to |num_or_id|, etc., have been chosen to
  1490. shorten some of the program logic; for example, the program makes use of
  1491. the fact that |sign+2=sign_val_sign|.
  1492. @d misc=0 {state associated with special characters}
  1493. @d num_or_id=1 {state associated with numbers and identifiers}
  1494. @d sign=2 {state associated with pending \.+ or \.-}
  1495. @d sign_val=num_or_id+2 {state associated with pending sign and value}
  1496. @d sign_val_sign=sign+2 {|sign_val| followed by another pending sign}
  1497. @d sign_val_val=sign_val+2 {|sign_val| followed by another pending value}
  1498. @d unbreakable=sign_val_val+1 {state associated with \.{@@\&}}
  1499. @<Globals...@>=
  1500. @!out_state:eight_bits; {current status of partial output}
  1501. @!out_val,@!out_app:integer; {pending values}
  1502. @!out_sign:ASCII_code; {sign to use if appending |out_val>=0|}
  1503. @!last_sign:-1..+1; {sign to use if appending a zero}
  1504. @ During the output process, |line| will equal the number of the next line
  1505. to be output.
  1506. @<Initialize the output buffer@>=
  1507. out_state:=misc; out_ptr:=0; break_ptr:=0; semi_ptr:=0; out_buf[0]:=0; line:=1;
  1508. @ Here is a routine that is invoked when |out_ptr>line_length|
  1509. or when it is time to flush out the final line. The |flush_buffer| procedure
  1510. often writes out the line up to the current |break_ptr| position, then moves the
  1511. remaining information to the front of |out_buf|. However, it prefers to
  1512. write only up to |semi_ptr|, if the residual line won't be too long.
  1513. @d check_break==if out_ptr>line_length then flush_buffer
  1514. @p procedure flush_buffer; {writes one line to output file}
  1515. var k:0..out_buf_size; {index into |out_buf|}
  1516. @!b:0..out_buf_size; {value of |break_ptr| upon entry}
  1517. begin b:=break_ptr;
  1518. if (semi_ptr<>0)and(out_ptr-semi_ptr<=line_length) then break_ptr:=semi_ptr;
  1519. for k:=1 to break_ptr do write(Pascal_file,xchr[out_buf[k-1]]);
  1520. write_ln(Pascal_file); incr(line);
  1521. if line mod 100 = 0 then
  1522.   begin print('.');
  1523.   if line mod 500 = 0 then print(line:1);
  1524.   update_terminal; {progress report}
  1525.   end;
  1526. if break_ptr<out_ptr then
  1527.   begin if out_buf[break_ptr]=" " then
  1528.     begin incr(break_ptr); {drop space at break}
  1529.     if break_ptr>b then b:=break_ptr;
  1530.     end;
  1531.   for k:=break_ptr to out_ptr-1 do out_buf[k-break_ptr]:=out_buf[k];
  1532.   end;
  1533. out_ptr:=out_ptr-break_ptr; break_ptr:=b-break_ptr; semi_ptr:=0;
  1534. if out_ptr>line_length then
  1535.   begin err_print('! Long line must be truncated'); out_ptr:=line_length;
  1536. @.Long line must be truncated@>
  1537.   end;
  1538. @ @<Empty the last line from the buffer@>=
  1539. break_ptr:=out_ptr; semi_ptr:=0; flush_buffer;
  1540. if brace_level<>0 then
  1541.   err_print('! Program ended at brace level ',brace_level:1);
  1542. @.Program ended at brace level n@>
  1543. @ Another simple and useful routine appends the decimal equivalent of
  1544. a nonnegative integer to the output buffer.
  1545. @d app(#)==begin out_buf[out_ptr]:=#; incr(out_ptr); {append a single character}
  1546.   end
  1547. @p procedure app_val(@!v:integer); {puts |v| into buffer, assumes |v>=0|}
  1548. var k:0..out_buf_size; {index into |out_buf|}
  1549. begin k:=out_buf_size; {first we put the digits at the very end of |out_buf|}
  1550. repeat out_buf[k]:=v mod 10; v:=v div 10; decr(k);
  1551. until v=0;
  1552. repeat incr(k); app(out_buf[k]+"0");
  1553. until k=out_buf_size; {then we append them, most significant first}
  1554. @ The output states are kept up to date by the output routines, which are
  1555. called |send_out|, |send_val|, and |send_sign|. The |send_out| procedure
  1556. has two parameters: |t| tells the type of information being sent and
  1557. |v| contains the information proper. Some information may also be passed
  1558. in the array |out_contrib|.
  1559. \yskip\hang If |t=misc| then |v| is a character to be output.
  1560. \hang If |t=str| then |v| is the length of a string or something like `\.{<>}'
  1561. in |out_contrib|.
  1562. \hang If |t=ident| then |v| is the length of an identifier in |out_contrib|.
  1563. \hang If |t=frac| then |v| is the length of a fraction and/or exponent in
  1564. |out_contrib|.
  1565. @d str=1 {|send_out| code for a string}
  1566. @d ident=2 {|send_out| code for an identifier}
  1567. @d frac=3 {|send_out| code for a fraction}
  1568. @<Glob...@>=
  1569. @!out_contrib:array[1..line_length] of ASCII_code; {a contribution to |out_buf|}
  1570. @ A slightly subtle point in the following code is that the user may ask
  1571. for a |join| operation (i.e., \.{@@\&}) following whatever is being sent
  1572. out.  We will see later that |join| is implemented in part by calling
  1573. |send_out(frac,0)|.
  1574. @p procedure send_out(@!t:eight_bits; @!v:sixteen_bits);
  1575.   {outputs |v| of type |t|}
  1576. label restart;
  1577. var k: 0..line_length; {index into |out_contrib|}
  1578. begin @<Get the buffer ready for appending the new information@>;
  1579. if t<>misc then for k:=1 to v do app(out_contrib[k])
  1580. else app(v);
  1581. check_break;
  1582. if (t=misc)and((v=";")or(v="}")) then
  1583.   begin semi_ptr:=out_ptr; break_ptr:=out_ptr;
  1584.   end;
  1585. if t>=ident then out_state:=num_or_id {|t=ident| or |frac|}
  1586. else out_state:=misc {|t=str| or |misc|}
  1587. @ Here is where the buffer states for signs and values collapse into simpler
  1588. states, because we are about to append something that doesn't combine with
  1589. the previous integer constants.
  1590. We use an ASCII-code trick: Since |","-1="+"| and |","+1="-"|, we have
  1591. |","-c=@t sign of $c$@>|, when $\vert c\vert=1$.
  1592. @<Get the buffer ready...@>=
  1593. restart: case out_state of
  1594. num_or_id: if t<>frac then
  1595.   begin break_ptr:=out_ptr;
  1596.   if t=ident then app(" ");
  1597.   end;
  1598. sign: begin app(","-out_app); check_break; break_ptr:=out_ptr;
  1599.   end;
  1600. sign_val,sign_val_sign: begin @<Append \(|out_val| to buffer@>;
  1601.   out_state:=out_state-2; goto restart;
  1602.   end;
  1603. sign_val_val: @<Reduce |sign_val_val| to |sign_val| and |goto restart|@>;
  1604. misc: if t<>frac then break_ptr:=out_ptr;@/
  1605. othercases do_nothing {this is for |unbreakable| state}
  1606. endcases
  1607. @ @<Append \(|out_val|...@>=
  1608. if (out_val<0)or((out_val=0)and(last_sign<0)) then app("-")
  1609. else if out_sign>0 then app(out_sign);
  1610. app_val(abs(out_val)); check_break;
  1611. @ @<Reduce |sign_val_val|...@>=
  1612. begin if (t=frac)or(@<Contribution is \.* or \./ or \.{DIV} or \.{MOD}@>) then
  1613.   begin @<Append \(|out_val| to buffer@>;
  1614.   out_sign:="+"; out_val:=out_app;
  1615.   end
  1616. else out_val:=out_val+out_app;
  1617. out_state:=sign_val; goto restart;
  1618. @ @<Contribution is \.*...@>=
  1619. ((t=ident)and(v=3)and@|
  1620.  (((out_contrib[1]="D")and(out_contrib[2]="I")and(out_contrib[3]="V")) or@|
  1621.  ((out_contrib[1]="M")and(out_contrib[2]="O")and(out_contrib[3]="D")) ))or@|
  1622. @^uppercase@>
  1623.  ((t=misc)and((v="*")or(v="/")))
  1624. @ The following routine is called with $v=\pm1$ when a plus or minus sign is
  1625. appended to the output. It extends \PASCAL\ to allow repeated signs
  1626. (e.g., `\.{--}' is equivalent to `\.+'), rather than to give an error message.
  1627. The signs following `\.E' in real constants are treated as part of a fraction,
  1628. so they are not seen by this routine.
  1629. @p procedure send_sign(@!v:integer);
  1630. begin case out_state of
  1631. sign, sign_val_sign: out_app:=out_app*v;
  1632. sign_val:begin out_app:=v; out_state:=sign_val_sign;
  1633.   end;
  1634. sign_val_val: begin out_val:=out_val+out_app; out_app:=v;
  1635.   out_state:=sign_val_sign;
  1636.   end;
  1637. othercases begin break_ptr:=out_ptr; out_app:=v; out_state:=sign;
  1638.   end
  1639. endcases;@/
  1640. last_sign:=out_app;
  1641. @ When a (signed) integer value is to be output, we call |send_val|.
  1642. @d bad_case=666 {this is a label used below}
  1643. @p procedure send_val(@!v:integer); {output the (signed) value |v|}
  1644. label bad_case, {go here if we can't keep |v| in the output state}
  1645.   exit;
  1646. begin case out_state of
  1647. num_or_id: begin @<If previous output was \.{DIV} or \.{MOD}, |goto bad_case|@>;
  1648.   out_sign:=" "; out_state:=sign_val; out_val:=v; break_ptr:=out_ptr;
  1649.   last_sign:=+1;
  1650.   end;
  1651. misc: begin @<If previous output was \.* or \./, |goto bad_case|@>;
  1652.   out_sign:=0; out_state:=sign_val; out_val:=v; break_ptr:=out_ptr;
  1653.   last_sign:=+1;
  1654.   end;
  1655. @t\4@>@<Handle cases of |send_val| when |out_state| contains a sign@>@;
  1656. othercases goto bad_case
  1657. endcases;@/
  1658. return;
  1659. bad_case: @<Append the decimal value of |v|, with parentheses if negative@>;
  1660. exit: end;
  1661. @ @<Handle cases of |send_val|...@>=
  1662. sign: begin out_sign:="+"; out_state:=sign_val; out_val:=out_app*v;
  1663.   end;
  1664. sign_val: begin out_state:=sign_val_val; out_app:=v;
  1665.   err_print('! Two numbers occurred without a sign between them');
  1666.   end;
  1667. sign_val_sign: begin out_state:=sign_val_val; out_app:=out_app*v;
  1668.   end;
  1669. sign_val_val: begin out_val:=out_val+out_app; out_app:=v;
  1670.   err_print('! Two numbers occurred without a sign between them');
  1671. @.Two numbers occurred...@>
  1672.   end;
  1673. @ @<If previous output was \.*...@>=
  1674. if (out_ptr=break_ptr+1)and((out_buf[break_ptr]="*")or(out_buf[break_ptr]="/"))
  1675.   then goto bad_case
  1676. @ @<If previous output was \.{DIV}...@>=
  1677. if (out_ptr=break_ptr+3)or
  1678.  ((out_ptr=break_ptr+4)and(out_buf[break_ptr]=" ")) then
  1679. @^uppercase@>
  1680.   if ((out_buf[out_ptr-3]="D")and(out_buf[out_ptr-2]="I")and
  1681.     (out_buf[out_ptr-1]="V"))or @/
  1682.      ((out_buf[out_ptr-3]="M")and(out_buf[out_ptr-2]="O")and
  1683.     (out_buf[out_ptr-1]="D")) then@/ goto bad_case
  1684. @ @<Append the decimal value...@>=
  1685. if v>=0 then
  1686.   begin if out_state=num_or_id then
  1687.     begin break_ptr:=out_ptr; app(" ");
  1688.     end;
  1689.   app_val(v); check_break; out_state:=num_or_id;
  1690.   end
  1691. else  begin app("("); app("-"); app_val(-v); app(")"); check_break;
  1692.   out_state:=misc;
  1693.   end
  1694. @* The big output switch.
  1695. To complete the output process, we need a routine that takes the results
  1696. of |get_output| and feeds them to |send_out|, |send_val|, or |send_sign|.
  1697. This procedure `|send_the_output|' will be invoked just once, as follows:
  1698. @<Phase II: Output the contents of the compressed tables@>=
  1699. if text_link[0]=0 then
  1700.   begin print_nl('! No output was specified.'); mark_harmless;
  1701. @.No output was specified@>
  1702.   end
  1703. else  begin print_nl('Writing the output file'); update_terminal;@/
  1704.   @<Initialize the output stacks@>;
  1705.   @<Initialize the output buffer@>;
  1706.   send_the_output;@/
  1707.   @<Empty the last line...@>;
  1708.   print_nl('Done.');
  1709.   end
  1710. @ A many-way switch is used to send the output:
  1711. @d get_fraction=2 {this label is used below}
  1712. @p procedure send_the_output;
  1713. label get_fraction, {go here to finish scanning a real constant}
  1714.   reswitch, continue;
  1715. var cur_char:eight_bits; {the latest character received}
  1716.   @!k:0..line_length; {index into |out_contrib|}
  1717.   @!j:0..max_bytes; {index into |byte_mem|}
  1718.   @!w:0..ww-1; {segment of |byte_mem|}
  1719.   @!n:integer; {number being scanned}
  1720. begin while stack_ptr>0 do
  1721.   begin cur_char:=get_output;
  1722.   reswitch: case cur_char of
  1723.   0: do_nothing; {this case might arise if output ends unexpectedly}
  1724.   @t\4@>@<Cases related to identifiers@>@;
  1725.   @t\4@>@<Cases related to constants, possibly leading to
  1726.     |get_fraction| or |reswitch|@>@;
  1727.   "+","-": send_sign(","-cur_char);
  1728.   @t\4@>@<Cases like \.{<>} and \.{:=}@>@;
  1729.   "'": @<Send a string, |goto reswitch|@>;
  1730.   @<Other printable characters@>: send_out(misc,cur_char);
  1731.   @t\4@>@<Cases involving \.{@@\{} and \.{@@\}}@>@;
  1732.   join: begin send_out(frac,0); out_state:=unbreakable;
  1733.     end;
  1734.   verbatim: @<Send verbatim string@>;
  1735.   force_line: @<Force a line break@>;
  1736.   othercases err_print('! Can''t output ASCII code ',cur_char:1)
  1737. @.Can't output ASCII code n@>
  1738.   endcases;@/
  1739.   goto continue;
  1740.   get_fraction: @<Special code to finish real constants@>;
  1741.   continue: end;
  1742. @ @<Cases like \.{<>}...@>=
  1743. and_sign: begin out_contrib[1]:="A"; out_contrib[2]:="N"; out_contrib[3]:="D";
  1744. @^uppercase@>
  1745.   send_out(ident,3);
  1746.   end;
  1747. not_sign: begin out_contrib[1]:="N"; out_contrib[2]:="O"; out_contrib[3]:="T";
  1748.   send_out(ident,3);
  1749.   end;
  1750. set_element_sign: begin out_contrib[1]:="I"; out_contrib[2]:="N";
  1751.   send_out(ident,2);
  1752.   end;
  1753. or_sign: begin out_contrib[1]:="O"; out_contrib[2]:="R"; send_out(ident,2);
  1754.   end;
  1755. left_arrow: begin out_contrib[1]:=":"; out_contrib[2]:="="; send_out(str,2);
  1756.   end;
  1757. not_equal: begin out_contrib[1]:="<"; out_contrib[2]:=">"; send_out(str,2);
  1758.   end;
  1759. less_or_equal: begin out_contrib[1]:="<"; out_contrib[2]:="="; send_out(str,2);
  1760.   end;
  1761. greater_or_equal: begin out_contrib[1]:=">"; out_contrib[2]:="=";
  1762.   send_out(str,2);
  1763.   end;
  1764. equivalence_sign: begin out_contrib[1]:="="; out_contrib[2]:="=";
  1765.   send_out(str,2);
  1766.   end;
  1767. double_dot: begin out_contrib[1]:="."; out_contrib[2]:="."; send_out(str,2);
  1768.   end;
  1769. @ Please don't ask how all of the following characters can actually get
  1770. through \.{TANGLE} outside of strings. It seems that |""""| and |"{"|
  1771. cannot actually occur at this point of the program, but they have
  1772. been included just in case \.{TANGLE} changes.
  1773. If \.{TANGLE} is producing code for a \PASCAL\ compiler that uses `\.{(.}'
  1774. and `\.{.)}' instead of square brackets (e.g., on machines with {\mc EBCDIC}
  1775. code), one should remove |"["| and |"]"| from this list and put them into
  1776. the preceding module in the appropriate way. Similarly, some compilers
  1777. want `\.\^' to be converted to `\.{@@}'.
  1778. @^system dependencies@>@^EBCDIC@>
  1779. @<Other printable characters@>=
  1780. "!","""","#","$","%","&","(",")","*",",","/",":",";","<","=",">","?",
  1781. "@@","[","\","]","^","_","`","{","|"
  1782. @ Single-character identifiers represent themselves, while longer ones
  1783. appear in |byte_mem|. All must be converted to uppercase,
  1784. with underlines removed. Extremely long identifiers must be chopped.
  1785. (Some \PASCAL\ compilers work with lowercase letters instead of
  1786. uppercase. If this module of \.{TANGLE} is changed, it's also necessary
  1787. to change from uppercase to lowercase in the modules that are
  1788. listed in the index under ``uppercase''.)
  1789. @^system dependencies@>
  1790. @^uppercase@>
  1791. @d up_to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
  1792.   #-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#
  1793. @<Cases related to identifiers@>=
  1794. "A",up_to("Z"): begin out_contrib[1]:=cur_char; send_out(ident,1);
  1795.   end;
  1796. "a",up_to("z"): begin out_contrib[1]:=cur_char-@'40; send_out(ident,1);
  1797.   end;
  1798. identifier: begin k:=0; j:=byte_start[cur_val]; w:=cur_val mod ww;
  1799.   while (k<max_id_length)and(j<byte_start[cur_val+ww]) do
  1800.     begin incr(k); out_contrib[k]:=byte_mem[w,j]; incr(j);
  1801.     if out_contrib[k]>="a" then out_contrib[k]:=out_contrib[k]-@'40
  1802.     else if out_contrib[k]="_" then decr(k);
  1803.     end;
  1804.   send_out(ident,k);
  1805.   end;
  1806. @ After sending a string, we need to look ahead at the next character, in order
  1807. to see if there were two consecutive single-quote marks. Afterwards we go to
  1808. |reswitch| to process the next character.
  1809. @<Send a string...@>=
  1810. begin k:=1; out_contrib[1]:="'";
  1811. repeat if k<line_length then incr(k);
  1812. out_contrib[k]:=get_output;
  1813. until (out_contrib[k]="'")or(stack_ptr=0);
  1814. if k=line_length then err_print('! String too long');
  1815. @.String too long@>
  1816. send_out(str,k); cur_char:=get_output;
  1817. if cur_char="'" then out_state:=unbreakable;
  1818. goto reswitch;
  1819. @ Sending a verbatim string is similar, but we don't have to look ahead.
  1820. @<Send verbatim string@>=
  1821. begin k:=0;
  1822. repeat if k<line_length then incr(k);
  1823. out_contrib[k]:=get_output;
  1824. until (out_contrib[k]=verbatim)or(stack_ptr=0);
  1825. if k=line_length then err_print('! Verbatim string too long');
  1826. @.Verbatim string too long@>
  1827. send_out(str,k-1);
  1828. @ In order to encourage portable software, \.{TANGLE} complains
  1829. if the constants get dangerously close to the largest value representable
  1830. on a 32-bit computer ($2^{31}-1$).
  1831. @d digits=="0","1","2","3","4","5","6","7","8","9"
  1832. @<Cases related to constants...@>=
  1833. digits: begin n:=0;
  1834.   repeat cur_char:=cur_char-"0";
  1835.   if n>=@'1463146314 then err_print('! Constant too big')
  1836. @.Constant too big@>
  1837.   else n:=10*n+cur_char;
  1838.   cur_char:=get_output;
  1839.   until (cur_char>"9")or(cur_char<"0");
  1840.   send_val(n); k:=0;
  1841.   if cur_char="e" then cur_char:="E";
  1842. @^uppercase@>
  1843.   if cur_char="E" then goto get_fraction
  1844.   else goto reswitch;
  1845.   end;
  1846. check_sum: send_val(pool_check_sum);
  1847. octal: begin n:=0; cur_char:="0";
  1848.   repeat cur_char:=cur_char-"0";
  1849.   if n>=@'2000000000 then err_print('! Constant too big')
  1850.   else n:=8*n+cur_char;
  1851.   cur_char:=get_output;
  1852.   until (cur_char>"7")or(cur_char<"0");
  1853.   send_val(n); goto reswitch;
  1854.   end;
  1855. hex: begin n:=0; cur_char:="0";
  1856.   repeat if cur_char>="A" then cur_char:=cur_char+10-"A"
  1857.   else cur_char:=cur_char-"0";
  1858.   if n>=@"8000000 then err_print('! Constant too big')
  1859.   else n:=16*n+cur_char;
  1860.   cur_char:=get_output;
  1861.   until (cur_char>"F")or(cur_char<"0")or@|
  1862.     ((cur_char>"9")and(cur_char<"A"));
  1863.   send_val(n); goto reswitch;
  1864.   end;
  1865. number: send_val(cur_val);
  1866. ".":  begin k:=1; out_contrib[1]:="."; cur_char:=get_output;
  1867.   if cur_char="." then
  1868.     begin out_contrib[2]:="."; send_out(str,2);
  1869.     end
  1870.   else if (cur_char>="0")and(cur_char<="9") then goto get_fraction
  1871.   else  begin send_out(misc,"."); goto reswitch;
  1872.     end;
  1873.   end;
  1874. @ The following code appears at label `|get_fraction|', when we want to
  1875. scan to the end of a real constant. The first |k| characters of a fraction
  1876. have already been placed in |out_contrib|, and |cur_char| is the next character.
  1877. @<Special code...@>=
  1878. repeat if k<line_length then incr(k);
  1879. out_contrib[k]:=cur_char; cur_char:=get_output;
  1880. if (out_contrib[k]="E")and((cur_char="+")or(cur_char="-")) then
  1881. @^uppercase@>
  1882.   begin if k<line_length then incr(k);
  1883.   out_contrib[k]:=cur_char; cur_char:=get_output;
  1884.   end
  1885. else if cur_char="e" then cur_char:="E";
  1886. until (cur_char<>"E")and((cur_char<"0")or(cur_char>"9"));
  1887. if k=line_length then err_print('! Fraction too long');
  1888. @.Fraction too long@>
  1889. send_out(frac,k); goto reswitch
  1890. @ Some \PASCAL\ compilers do not recognize comments in braces, so the
  1891. comments must be delimited by `\.{(*}' and `\.{*)}'.
  1892. @^system dependencies@>
  1893. In such cases the statement `|send_out(misc,"{")|' that appears here should
  1894. be replaced by `\ignorespaces|begin out_contrib[1]:="("; out_contrib[2]:="*";
  1895. send_out(str,2); end|', and a similar change should be made to
  1896. `|send_out(misc,"}")|'.
  1897. @<Cases involving \.{@@\{} and \.{@@\}}@>=
  1898. begin_comment: begin if brace_level=0 then send_out(misc,"{")
  1899.   else send_out(misc,"[");
  1900.   incr(brace_level);
  1901.   end;
  1902. end_comment: if brace_level>0 then
  1903.     begin decr(brace_level);
  1904.     if brace_level=0 then send_out(misc,"}")
  1905.     else send_out(misc,"]");
  1906.     end
  1907.   else err_print('! Extra @@}');
  1908. @.Extra \AT!\}@>
  1909. module_number: begin if brace_level=0 then send_out(misc,"{")
  1910.   else send_out(misc,"[");
  1911.   if cur_val<0 then
  1912.     begin send_out(misc,":"); send_val(-cur_val);
  1913.     end
  1914.   else  begin send_val(cur_val); send_out(misc,":");
  1915.     end;
  1916.   if brace_level=0 then send_out(misc,"}")
  1917.   else send_out(misc,"]");
  1918.   end;
  1919. @ @<Force a line break@>=
  1920. begin send_out(str,0); {normalize the buffer}
  1921. while out_ptr>0 do
  1922.   begin if out_ptr<=line_length then break_ptr:=out_ptr;
  1923.   flush_buffer;
  1924.   end;
  1925. out_state:=misc;
  1926. @* Introduction to the input phase.
  1927. We have now seen that \.{TANGLE} will be able to output the full
  1928. \PASCAL\ program, if we can only get that program into the byte memory in
  1929. the proper format. The input process is something like the output process
  1930. in reverse, since we compress the text as we read it in and we expand it
  1931. as we write it out.
  1932. There are three main input routines. The most interesting is the one that gets
  1933. the next token of a \PASCAL\ text; the other two are used to scan rapidly past
  1934. \TeX\ text in the \.{WEB} source code. One of the latter routines will jump to
  1935. the next token that starts with `\.{@@}', and the other skips to the end
  1936. of a \PASCAL\ comment.
  1937. @ But first we need to consider the low-level routine |get_line|
  1938. that takes care of merging |change_file| into |web_file|. The |get_line|
  1939. procedure also updates the line numbers for error messages.
  1940. @<Globals...@>=
  1941. @!line:integer; {the number of the current line in the current file}
  1942. @!other_line:integer; {the number of the current line in the input file that
  1943.   is not currently being read}
  1944. @!temp_line:integer; {used when interchanging |line| with |other_line|}
  1945. @!limit:0..buf_size; {the last character position occupied in the buffer}
  1946. @!loc:0..buf_size; {the next character position to be read from the buffer}
  1947. @!input_has_ended: boolean; {if |true|, there is no more input}
  1948. @!changing: boolean; {if |true|, the current line is from |change_file|}
  1949. @ As we change |changing| from |true| to |false| and back again, we must
  1950. remember to swap the values of |line| and |other_line| so that the |err_print|
  1951. routine will be sure to report the correct line number.
  1952. @d change_changing==
  1953.   changing := not changing;
  1954.   temp_line:=other_line; other_line:=line; line:=temp_line
  1955.     {|line @t$\null\BA\null$@> other_line|}
  1956. @ When |changing| is |false|, the next line of |change_file| is kept in
  1957. |change_buffer[0..change_limit]|, for purposes of comparison with the next
  1958. line of |web_file|. After the change file has been completely input, we
  1959. set |change_limit:=0|, so that no further matches will be made.
  1960. @<Globals...@>=
  1961. @!change_buffer:array[0..buf_size] of ASCII_code;
  1962. @!change_limit:0..buf_size; {the last position occupied in |change_buffer|}
  1963. @ Here's a simple function that checks if the two buffers are different.
  1964. @p function lines_dont_match:boolean;
  1965. label exit;
  1966. var k:0..buf_size; {index into the buffers}
  1967. begin lines_dont_match:=true;
  1968. if change_limit<>limit then return;
  1969. if limit>0 then
  1970.   for k:=0 to limit-1 do if change_buffer[k]<>buffer[k] then return;
  1971. lines_dont_match:=false;
  1972. exit: end;
  1973. @ Procedure |prime_the_change_buffer| sets |change_buffer| in preparation
  1974. for the next matching operation. Since blank lines in the change file are
  1975. not used for matching, we have |(change_limit=0)and not changing| if and
  1976. only if the change file is exhausted. This procedure is called only
  1977. when |changing| is true; hence error messages will be reported correctly.
  1978. @p procedure prime_the_change_buffer;
  1979. label continue, done, exit;
  1980. var k:0..buf_size; {index into the buffers}
  1981. begin change_limit:=0; {this value will be used if the change file ends}
  1982. @<Skip over comment lines in the change file; |return| if end of file@>;
  1983. @<Skip to the next nonblank line; |return| if end of file@>;
  1984. @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  1985. exit: end;
  1986. @ While looking for a line that begins with \.{@@x} in the change file,
  1987. we allow lines that begin with \.{@@}, as long as they don't begin with
  1988. \.{@@y} or \.{@@z} (which would probably indicate that the change file is
  1989. fouled up).
  1990. @<Skip over comment lines in the change file...@>=
  1991. loop@+  begin incr(line);
  1992.   if not input_ln(change_file) then return;
  1993.   if limit<2 then goto continue;
  1994.   if buffer[0]<>"@@" then goto continue;
  1995.   if (buffer[1]>="X")and(buffer[1]<="Z") then
  1996.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1997.   if buffer[1]="x" then goto done;
  1998.   if (buffer[1]="y")or(buffer[1]="z") then
  1999.     begin loc:=2; err_print('! Where is the matching @@x?');
  2000. @.Where is the match...@>
  2001.     end;
  2002. continue: end;
  2003. done:
  2004. @ Here we are looking at lines following the \.{@@x}.
  2005. @<Skip to the next nonblank line...@>=
  2006. repeat incr(line);
  2007.   if not input_ln(change_file) then
  2008.     begin err_print('! Change file ended after @@x');
  2009. @.Change file ended...@>
  2010.     return;
  2011.     end;
  2012. until limit>0;
  2013. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  2014. begin change_limit:=limit;
  2015. if limit>0 then for k:=0 to limit-1 do change_buffer[k]:=buffer[k];
  2016. @ The following procedure is used to see if the next change entry should
  2017. go into effect; it is called only when |changing| is false.
  2018. The idea is to test whether or not the current
  2019. contents of |buffer| matches the current contents of |change_buffer|.
  2020. If not, there's nothing more to do; but if so, a change is called for:
  2021. All of the text down to the \.{@@y} is supposed to match. An error
  2022. message is issued if any discrepancy is found. Then the procedure
  2023. prepares to read the next line from |change_file|.
  2024. @p procedure check_change; {switches to |change_file| if the buffers match}
  2025. label exit;
  2026. var n:integer; {the number of discrepancies found}
  2027. @!k:0..buf_size; {index into the buffers}
  2028. begin if lines_dont_match then return;
  2029. n:=0;
  2030. loop@+  begin change_changing; {now it's |true|}
  2031.   incr(line);
  2032.   if not input_ln(change_file) then
  2033.     begin err_print('! Change file ended before @@y');
  2034. @.Change file ended...@>
  2035.     change_limit:=0;  change_changing; {|false| again}
  2036.     return;
  2037.     end;
  2038.   @<If the current line starts with \.{@@y},
  2039.     report any discrepancies and |return|@>;
  2040.   @<Move |buffer| and |limit|...@>;
  2041.   change_changing; {now it's |false|}
  2042.   incr(line);
  2043.   if not input_ln(web_file) then
  2044.     begin err_print('! WEB file ended during a change');
  2045. @.WEB file ended...@>
  2046.     input_has_ended:=true; return;
  2047.     end;
  2048.   if lines_dont_match then incr(n);
  2049.   end;
  2050. exit: end;
  2051. @ @<If the current line starts with \.{@@y}...@>=
  2052. if limit>1 then if buffer[0]="@@" then
  2053.   begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  2054.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  2055.   if (buffer[1]="x")or(buffer[1]="z") then
  2056.     begin loc:=2; err_print('! Where is the matching @@y?');
  2057. @.Where is the match...@>
  2058.     end
  2059.   else if buffer[1]="y" then
  2060.     begin if n>0 then
  2061.       begin loc:=2; err_print('! Hmm... ',n:1,
  2062.         ' of the preceding lines failed to match');
  2063. @.Hmm... n of the preceding...@>
  2064.       end;
  2065.     return;
  2066.     end;
  2067.   end
  2068. @ @<Initialize the input system@>=
  2069. open_input; line:=0; other_line:=0;@/
  2070. changing:=true; prime_the_change_buffer; change_changing;@/
  2071. limit:=0; loc:=1; buffer[0]:=" "; input_has_ended:=false;
  2072. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  2073. line of merged input into the buffer and updates the other variables
  2074. appropriately. A space is placed at the right end of the line.
  2075. @p procedure get_line; {inputs the next line}
  2076. label restart;
  2077. begin restart: if changing then
  2078.   @<Read from |change_file| and maybe turn off |changing|@>;
  2079. if not changing then
  2080.   begin @<Read from |web_file| and maybe turn on |changing|@>;
  2081.   if changing then goto restart;
  2082.   end;
  2083. loc:=0; buffer[limit]:=" ";
  2084. @ @<Read from |web_file|...@>=
  2085. begin incr(line);
  2086. if not input_ln(web_file) then input_has_ended:=true
  2087. else if limit=change_limit then
  2088.   if buffer[0]=change_buffer[0] then
  2089.     if change_limit>0 then check_change;
  2090. @ @<Read from |change_file|...@>=
  2091. begin incr(line);
  2092. if not input_ln(change_file) then
  2093.   begin err_print('! Change file ended without @@z');
  2094. @.Change file ended...@>
  2095.   buffer[0]:="@@"; buffer[1]:="z"; limit:=2;
  2096.   end;
  2097. if limit>1 then {check if the change has ended}
  2098.   if buffer[0]="@@" then
  2099.     begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  2100.       buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  2101.     if (buffer[1]="x")or(buffer[1]="y") then
  2102.       begin loc:=2; err_print('! Where is the matching @@z?');
  2103. @.Where is the match...@>
  2104.       end
  2105.     else if buffer[1]="z" then
  2106.       begin prime_the_change_buffer; change_changing;
  2107.       end;
  2108.     end;
  2109. @ At the end of the program, we will tell the user if the change file
  2110. had a line that didn't match any relevant line in |web_file|.
  2111. @<Check that all changes have been read@>=
  2112. if change_limit<>0 then {|changing| is false}
  2113.   begin for loc:=0 to change_limit do buffer[loc]:=change_buffer[loc];
  2114.   limit:=change_limit; changing:=true; line:=other_line; loc:=change_limit;
  2115.   err_print('! Change file entry did not match');
  2116. @.Change file entry did not match@>
  2117.   end
  2118. @ Important milestones are reached during the input phase when certain
  2119. control codes are sensed.
  2120. Control codes in \.{WEB} begin with `\.{@@}', and the next character
  2121. identifies the code. Some of these are of interest only to \.{WEAVE},
  2122. so \.{TANGLE} ignores them; the others are converted by \.{TANGLE} into
  2123. internal code numbers by the |control_code| function below. The ordering
  2124. of these internal code numbers has been chosen to simplify the program logic;
  2125. larger numbers are given to the control codes that denote more significant
  2126. milestones.
  2127. @d ignore=0 {control code of no interest to \.{TANGLE}}
  2128. @d control_text=@'203 {control code for `\.{@@t}', `\.{@@\^}', etc.}
  2129. @d format=@'204 {control code for `\.{@@f}'}
  2130. @d definition=@'205 {control code for `\.{@@d}'}
  2131. @d begin_Pascal=@'206 {control code for `\.{@@p}'}
  2132. @d module_name=@'207 {control code for `\.{@@<}'}
  2133. @d new_module=@'210 {control code for `\.{@@\ }' and `\.{@@*}'}
  2134. @p function control_code(@!c:ASCII_code):eight_bits; {convert |c| after \.{@@}}
  2135. begin case c of
  2136. "@@": control_code:="@@"; {`quoted' at sign}
  2137. "'": control_code:=octal; {precedes octal constant}
  2138. """": control_code:=hex; {precedes hexadecimal constant}
  2139. "$": control_code:=check_sum; {string pool check sum}
  2140. " ",tab_mark: control_code:=new_module; {beginning of a new module}
  2141. "*": begin print('*',module_count+1:1);
  2142.   update_terminal; {print a progress report}
  2143.   control_code:=new_module; {beginning of a new module}
  2144.   end;
  2145. "D","d": control_code:=definition; {macro definition}
  2146. "F","f": control_code:=format; {format definition}
  2147. "{": control_code:=begin_comment; {begin-comment delimiter}
  2148. "}": control_code:=end_comment; {end-comment delimiter}
  2149. "P","p": control_code:=begin_Pascal; {\PASCAL\ text in unnamed module}
  2150. "T","t","^",".",":": control_code:=control_text; {control text to be ignored}
  2151. "&": control_code:=join; {concatenate two tokens}
  2152. "<": control_code:=module_name; {beginning of a module name}
  2153. "=": control_code:=verbatim; {beginning of \PASCAL\ verbatim mode}
  2154. "\": control_code:=force_line; {force a new line in \PASCAL\ output}
  2155. othercases control_code:=ignore {ignore all other cases}
  2156. endcases;
  2157. @ The |skip_ahead| procedure reads through the input at fairly high speed
  2158. until finding the next non-ignorable control code, which it returns.
  2159. @p function skip_ahead:eight_bits; {skip to next control code}
  2160. label done;
  2161. var c:eight_bits; {control code found}
  2162. begin loop begin if loc>limit then
  2163.     begin get_line;
  2164.     if input_has_ended then
  2165.       begin c:=new_module; goto done;
  2166.       end;
  2167.     end;
  2168.   buffer[limit+1]:="@@";
  2169.   while buffer[loc]<>"@@" do incr(loc);
  2170.   if loc<=limit then
  2171.     begin loc:=loc+2; c:=control_code(buffer[loc-1]);
  2172.     if (c<>ignore)or(buffer[loc-1]=">") then goto done;
  2173.     end;
  2174.   end;
  2175. done: skip_ahead:=c;
  2176. @ The |skip_comment| procedure reads through the input at somewhat high speed
  2177. until finding the first unmatched right brace or until coming to the end
  2178. of the file. It ignores characters following `\.\\' characters, since all
  2179. braces that aren't nested are supposed to be hidden in that way. For
  2180. example, consider the process of skipping the first comment below,
  2181. where the string containing the right brace has been typed as \.{\`\\.\\\}\'}
  2182. in the \.{WEB} file.
  2183. @p procedure skip_comment; {skips to next unmatched `\.\}'}
  2184. label exit;
  2185. var bal:eight_bits; {excess of left braces}
  2186. @!c:ASCII_code; {current character}
  2187. begin bal:=0;
  2188. loop@+  begin if loc>limit then
  2189.     begin get_line;
  2190.     if input_has_ended then
  2191.       begin err_print('! Input ended in mid-comment');
  2192. @.Input ended in mid-comment@>
  2193.       return;
  2194.       end;
  2195.     end;
  2196.   c:=buffer[loc]; incr(loc);
  2197.   @<Do special things when |c="@@", "\", "{", "}"|; |return| at end@>;
  2198.   end;
  2199. exit:end;
  2200. @ @<Do special things when |c="@@"...@>=
  2201. if c="@@" then
  2202.   begin c:=buffer[loc];
  2203.   if (c<>" ")and(c<>tab_mark)and(c<>"*")and(c<>"z")and(c<>"Z") then incr(loc)
  2204.   else  begin err_print('! Section ended in mid-comment');
  2205. @.Section ended in mid-comment@>
  2206.     decr(loc); return;
  2207.     end
  2208.   end
  2209. else if (c="\")and(buffer[loc]<>"@@") then incr(loc)
  2210. else if c="{" then incr(bal)
  2211. else if c="}" then
  2212.   begin if bal=0 then return;
  2213.   decr(bal);
  2214.   end
  2215. @* Inputting the next token.
  2216. As stated above, \.{TANGLE}'s most interesting input procedure is the
  2217. |get_next| routine that inputs the next token. However, the procedure
  2218. isn't especially difficult.
  2219. In most cases the tokens output by |get_next| have the form used in
  2220. replacement texts, except that two-byte tokens are not produced.
  2221. An identifier that isn't one letter long is represented by the
  2222. output `|identifier|', and in such a case the global variables
  2223. |id_first| and |id_loc| will have been set to the appropriate values
  2224. needed by the |id_lookup| procedure. A string that begins with a
  2225. double-quote is also considered an |identifier|, and in such a case
  2226. the global variable |double_chars| will also have been set appropriately.
  2227. Control codes produce the corresponding output of the |control_code|
  2228. function above; and if that code is |module_name|, the value of |cur_module|
  2229. will point to the |byte_start| entry for that module name.
  2230. Another global variable, |scanning_hex|, is |true| during the time that
  2231. the letters \.A through \.F should be treated as if they were digits.
  2232. @<Globals...@>=
  2233. @!cur_module: name_pointer; {name of module just scanned}
  2234. @!scanning_hex: boolean; {are we scanning a hexadecimal constant?}
  2235. @ @<Set init...@>=
  2236. scanning_hex:=false;
  2237. @ At the top level, |get_next| is a multi-way switch based on the next
  2238. character in the input buffer. A |new_module| code is inserted at the
  2239. very end of the input file.
  2240. @p function get_next:eight_bits; {produces the next input token}
  2241. label restart,done,found;
  2242. var c:eight_bits; {the current character}
  2243. @!d:eight_bits; {the next character}
  2244. @!j,@!k:0..longest_name; {indices into |mod_text|}
  2245. begin restart: if loc>limit then
  2246.   begin get_line;
  2247.   if input_has_ended then
  2248.     begin c:=new_module; goto found;
  2249.     end;
  2250.   end;
  2251. c:=buffer[loc]; incr(loc);
  2252. if scanning_hex then @<Go to |found| if |c| is a hexadecimal digit,
  2253.   otherwise set |scanning_hex:=false|@>;
  2254. case c of
  2255. "A",up_to("Z"),"a",up_to("z"): @<Get an identifier@>;
  2256. """": @<Get a preprocessed string@>;
  2257. "@@": @<Get control code and possible module name@>;
  2258. @t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
  2259. " ",tab_mark: goto restart; {ignore spaces and tabs}
  2260. "{": begin skip_comment; goto restart;
  2261.   end;
  2262. othercases if c>=128 then goto restart {ignore nonstandard characters}
  2263.   else do_nothing
  2264. endcases;
  2265. found:@!debug if trouble_shooting then debug_help;@;@+gubed@/
  2266. get_next:=c;
  2267. @ @<Go to |found| if |c| is a hexadecimal digit...@>=
  2268. if ((c>="0")and(c<="9"))or((c>="A")and(c<="F")) then goto found
  2269. else scanning_hex:=false
  2270. @ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
  2271. respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
  2272. for \TeX\ comments in \PASCAL\ text.
  2273. @d compress(#)==begin if loc<=limit then begin c:=#; incr(loc); end; end
  2274. @<Compress two-symbol...@>=
  2275. ".": if buffer[loc]="." then compress(double_dot)
  2276.   else if buffer[loc]=")" then compress("]");
  2277. ":": if buffer[loc]="=" then compress(left_arrow);
  2278. "=": if buffer[loc]="=" then compress(equivalence_sign);
  2279. ">": if buffer[loc]="=" then compress(greater_or_equal);
  2280. "<": if buffer[loc]="=" then compress(less_or_equal)
  2281.   else if buffer[loc]=">" then compress(not_equal);
  2282. "(": if buffer[loc]="*" then compress(begin_comment)
  2283.   else if buffer[loc]="." then compress("[");
  2284. "*": if buffer[loc]=")" then compress(end_comment);
  2285. @ We have to look at the preceding character to make sure this isn't part
  2286. of a real constant, before trying to find an identifier starting with
  2287. `\.e' or `\.E'.
  2288. @<Get an identifier@>=
  2289. begin if ((c="e")or(c="E"))and(loc>1) then
  2290.   if (buffer[loc-2]<="9")and(buffer[loc-2]>="0") then c:=0;
  2291. if c<>0 then
  2292.   begin decr(loc); id_first:=loc;
  2293.   repeat incr(loc); d:=buffer[loc];
  2294.   until ((d<"0")or((d>"9")and(d<"A"))or((d>"Z")and(d<"a"))or(d>"z")) and
  2295.     (d<>"_");
  2296.   if loc>id_first+1 then
  2297.     begin c:=identifier; id_loc:=loc;
  2298.     end;
  2299.   end
  2300. else c:="E"; {exponent of a real constant}
  2301. @ A string that starts and ends with double-quote marks is converted into
  2302. an identifier that behaves like a numeric macro by means of the following
  2303. piece of the program.
  2304. @^preprocessed strings@>
  2305. @<Get a preprocessed string@>=
  2306. begin double_chars:=0; id_first:=loc-1;
  2307. repeat d:=buffer[loc]; incr(loc);
  2308.   if (d="""")or(d="@@") then
  2309.     if buffer[loc]=d then
  2310.       begin incr(loc); d:=0; incr(double_chars);
  2311.       end
  2312.     else  begin if d="@@" then err_print('! Double @@ sign missing')
  2313. @.Double \AT! sign missing@>
  2314.       end
  2315.   else if loc>limit then
  2316.     begin err_print('! String constant didn''t end'); d:="""";
  2317. @.String constant didn't end@>
  2318.     end;
  2319. until d="""";
  2320. id_loc:=loc-1; c:=identifier;
  2321. @ After an \.{@@} sign has been scanned, the next character tells us
  2322. whether there is more work to do.
  2323. @<Get control code and possible module name@>=
  2324. begin c:=control_code(buffer[loc]); incr(loc);
  2325. if c=ignore then goto restart
  2326. else if c=hex then scanning_hex:=true
  2327. else if c=module_name then
  2328.   @<Scan the \(module name and make |cur_module| point to it@>
  2329. else if c=control_text then
  2330.   begin repeat c:=skip_ahead;
  2331.   until c<>"@@";
  2332.   if buffer[loc-1]<>">" then
  2333.     err_print('! Improper @@ within control text');
  2334. @.Improper \AT! within control text@>
  2335.   goto restart;
  2336.   end;
  2337. @ @<Scan the \(module name...@>=
  2338. begin @<Put module name into |mod_text[1..k]|@>;
  2339. if k>3 then
  2340.   begin if (mod_text[k]=".")and(mod_text[k-1]=".")and(mod_text[k-2]=".") then
  2341.     cur_module:=prefix_lookup(k-3)
  2342.   else cur_module:=mod_lookup(k);
  2343.   end
  2344. else cur_module:=mod_lookup(k);
  2345. @ Module names are placed into the |mod_text| array with consecutive spaces,
  2346. tabs, and carriage-returns replaced by single spaces. There will be no
  2347. spaces at the beginning or the end. (We set |mod_text[0]:=" "| to facilitate
  2348. this, since the |mod_lookup| routine uses |mod_text[1]| as the first
  2349. character of the name.)
  2350. @<Set init...@>=mod_text[0]:=" ";
  2351. @ @<Put module name...@>=
  2352. k:=0;
  2353. loop@+  begin if loc>limit then
  2354.     begin get_line;
  2355.     if input_has_ended then
  2356.       begin err_print('! Input ended in section name');
  2357. @.Input ended in section name@>
  2358.       goto done;
  2359.       end;
  2360.     end;
  2361.   d:=buffer[loc];
  2362.   @<If end of name, |goto done|@>;
  2363.   incr(loc); if k<longest_name-1 then incr(k);
  2364.   if (d=" ")or(d=tab_mark) then
  2365.     begin d:=" "; if mod_text[k-1]=" " then decr(k);
  2366.     end;
  2367.   mod_text[k]:=d;
  2368.   end;
  2369. done: @<Check for overlong name@>;
  2370. if (mod_text[k]=" ")and(k>0) then decr(k);
  2371. @ @<If end of name,...@>=
  2372. if d="@@" then
  2373.   begin d:=buffer[loc+1];
  2374.   if d=">" then
  2375.     begin loc:=loc+2; goto done;
  2376.     end;
  2377.   if (d=" ")or(d=tab_mark)or(d="*") then
  2378.     begin err_print('! Section name didn''t end'); goto done;
  2379. @.Section name didn't end@>
  2380.     end;
  2381.   incr(k); mod_text[k]:="@@"; incr(loc); {now |d=buffer[loc]| again}
  2382.   end
  2383. @ @<Check for overlong name@>=
  2384. if k>=longest_name-2 then
  2385.   begin print_nl('! Section name too long: ');
  2386. @.Section name too long@>
  2387.   for j:=1 to 25 do print(xchr[mod_text[j]]);
  2388.   print('...'); mark_harmless;
  2389.   end
  2390. @* Scanning a numeric definition.
  2391. When \.{TANGLE} looks at the \PASCAL\ text following the `\.=' of a numeric
  2392. macro definition, it calls on the precedure |scan_numeric(p)|, where |p|
  2393. points to the name that is to be defined. This procedure evaluates the
  2394. right-hand side, which must consist entirely of integer constants and
  2395. defined numeric macros connected with \.+ and \.- signs (no parentheses).
  2396. It also sets the global variable |next_control| to the control code that
  2397. terminated this definition.
  2398. A definition ends with the control codes |definition|, |format|, |module_name|,
  2399. |begin_Pascal|, and |new_module|, all of which can be recognized
  2400. by the fact that they are the largest values |get_next| can return.
  2401. @d end_of_definition(#)==(#>=format)
  2402.   {is |#| a control code ending a definition?}
  2403. @<Global...@>=
  2404. @!next_control:eight_bits; {control code waiting to be acted upon}
  2405. @ The evaluation of a numeric expression makes use of two variables called the
  2406. |accumulator| and the |next_sign|. At the beginning, |accumulator| is zero and
  2407. |next_sign| is $+1$. When a \.+ or \.- is scanned, |next_sign| is multiplied
  2408. by the value of that sign. When a numeric value is scanned, it is multiplied by
  2409. |next_sign| and added to the |accumulator|, then |next_sign| is reset to $+1$.
  2410. @d add_in(#)==begin accumulator:=accumulator+next_sign*(#); next_sign:=+1;
  2411.   end
  2412. @p procedure scan_numeric(@!p:name_pointer); {defines numeric macros}
  2413. label reswitch, done;
  2414. var accumulator:integer; {accumulates sums}
  2415. @!next_sign:-1..+1; {sign to attach to next value}
  2416. @!q:name_pointer; {points to identifiers being evaluated}
  2417. @!val:integer; {constants being evaluated}
  2418. begin @<Set \(|accumulator| to the value of the right-hand side@>;
  2419. if abs(accumulator)>=@'100000 then
  2420.   begin err_print('! Value too big: ',accumulator:1); accumulator:=0;
  2421. @.Value too big@>
  2422.   end;
  2423. equiv[p]:=accumulator+@'100000; {name |p| now is defined to equal |accumulator|}
  2424. @ @<Set \(|accumulator| to the value of the right-hand side@>=
  2425. accumulator:=0; next_sign:=+1;
  2426. loop@+  begin next_control:=get_next;
  2427.   reswitch: case next_control of
  2428.   digits: begin @<Set |val| to value of decimal constant, and
  2429.       set |next_control| to the following token@>;
  2430.     add_in(val); goto reswitch;
  2431.     end;
  2432.   octal: begin @<Set |val| to value of octal constant, and
  2433.       set |next_control| to the following token@>;
  2434.     add_in(val); goto reswitch;
  2435.     end;
  2436.   hex: begin @<Set |val| to value of hexadecimal constant, and
  2437.       set |next_control| to the following token@>;
  2438.     add_in(val); goto reswitch;
  2439.     end;
  2440.   identifier: begin q:=id_lookup(normal);
  2441.     if ilk[q]<>numeric then
  2442.       begin next_control:="*"; goto reswitch; {leads to error}
  2443.       end;
  2444.     add_in(equiv[q]-@'100000);
  2445.     end;
  2446.   "+": do_nothing;
  2447.   "-": next_sign:=-next_sign;
  2448.   format, definition, module_name, begin_Pascal, new_module: goto done;
  2449.   ";": err_print('! Omit semicolon in numeric definition');
  2450. @.Omit semicolon in numeric def...@>
  2451.   othercases @<Signal error, flush rest of the definition@>
  2452.   endcases;
  2453.   end;
  2454. done:
  2455. @ @<Signal error, flush rest...@>=
  2456. begin err_print('! Improper numeric definition will be flushed');
  2457. @.Improper numeric definition...@>
  2458. repeat next_control:=skip_ahead
  2459. until end_of_definition(next_control);
  2460. if next_control=module_name then
  2461.   begin {we want to scan the module name too}
  2462.   loc:=loc-2; next_control:=get_next;
  2463.   end;
  2464. accumulator:=0; goto done;
  2465. @ @<Set |val| to value of decimal...@>=
  2466. val:=0;
  2467. repeat val:=10*val+next_control-"0"; next_control:=get_next;
  2468. until (next_control>"9")or(next_control<"0")
  2469. @ @<Set |val| to value of octal...@>=
  2470. val:=0; next_control:="0";
  2471. repeat val:=8*val+next_control-"0"; next_control:=get_next;
  2472. until (next_control>"7")or(next_control<"0")
  2473. @ @<Set |val| to value of hex...@>=
  2474. val:=0; next_control:="0";
  2475. repeat if next_control>="A" then next_control:=next_control+"0"+10-"A";
  2476. val:=16*val+next_control-"0"; next_control:=get_next;
  2477. until (next_control>"F")or(next_control<"0")or@|
  2478.   ((next_control>"9")and(next_control<"A"))
  2479. @* Scanning a macro definition.
  2480. The rules for generating the replacement texts corresponding to simple
  2481. macros, parametric macros, and \PASCAL\ texts of a module are almost
  2482. identical, so a single procedure is used for all three cases. The
  2483. differences are that
  2484. \yskip\item{a)} The sign |#| denotes a parameter only when it appears
  2485. outside of strings in a parametric macro; otherwise it stands for the
  2486. ASCII character |#|. (This is not used in standard \PASCAL, but some
  2487. \PASCAL s allow, for example, `\.{/\#}' after a certain kind of file name.)
  2488. \item{b)}Module names are not allowed in simple macros or parametric macros;
  2489. in fact, the appearance of a module name terminates such macros and denotes
  2490. the name of the current module.
  2491. \item{c)}The symbols \.{@@d} and \.{@@f} and \.{@@p} are not allowed after
  2492. module names, while they terminate macro definitions.
  2493. @ Therefore there is a procedure |scan_repl| whose parameter |t| specifies
  2494. either |simple| or |parametric| or |module_name|. After |scan_repl| has
  2495. acted, |cur_repl_text| will point to the replacement text just generated, and
  2496. |next_control| will contain the control code that terminated the activity.
  2497. @<Globals...@>=
  2498. @!cur_repl_text:text_pointer; {replacement text formed by |scan_repl|}
  2499. @ @p procedure scan_repl(@!t:eight_bits); {creates a replacement text}
  2500. label continue, done, found;
  2501. var a:sixteen_bits; {the current token}
  2502. @!b:ASCII_code; {a character from the buffer}
  2503. @!bal:eight_bits; {left parentheses minus right parentheses}
  2504. begin bal:=0;
  2505. loop@+  begin continue: a:=get_next;
  2506.   case a of
  2507.   "(": incr(bal);
  2508.   ")": if bal=0 then err_print('! Extra )')
  2509. @.Extra )@>
  2510.     else decr(bal);
  2511.   "'": @<Copy a string from the buffer to |tok_mem|@>;
  2512.   "#": if t=parametric then a:=param;
  2513.   @t\4@>@<In cases that |a| is a non-ASCII token (|identifier|,
  2514.   |module_name|, etc.), either process it and change |a| to a byte
  2515.   that should be stored, or |goto continue| if |a| should be ignored,
  2516.   or |goto done| if |a| signals the end of this replacement text@>@;
  2517.   othercases do_nothing
  2518.   endcases;@/
  2519.   app_repl(a); {store |a| in |tok_mem|}
  2520.   end;
  2521. done: next_control:=a;
  2522. @<Make sure the parentheses balance@>;
  2523. if text_ptr>max_texts-zz then overflow('text');
  2524. cur_repl_text:=text_ptr; tok_start[text_ptr+zz]:=tok_ptr[z];
  2525. incr(text_ptr);
  2526. if z=zz-1 then z:=0@+else incr(z);
  2527. @ @<Make sure the parentheses balance@>=
  2528. if bal>0 then
  2529.   begin if bal=1 then err_print('! Missing )')
  2530.   else err_print('! Missing ',bal:1,' )''s');
  2531. @.Missing n )@>
  2532.   while bal>0 do
  2533.     begin app_repl(")"); decr(bal);
  2534.     end;
  2535.   end
  2536. @ @<In cases that |a| is...@>=
  2537. identifier: begin a:=id_lookup(normal); app_repl((a div @'400)+@'200);
  2538.   a:=a mod @'400;
  2539.   end;
  2540. module_name: if t<>module_name then goto done
  2541.   else  begin app_repl((cur_module div @'400)+@'250);
  2542.     a:=cur_module mod @'400;
  2543.     end;
  2544. verbatim: @<Copy verbatim string from the buffer to |tok_mem|@>;
  2545. definition, format, begin_Pascal: if t<>module_name then goto done
  2546.   else  begin err_print('! @@',xchr[buffer[loc-1]],
  2547. @.\AT!p is ignored in Pascal text@>
  2548. @.\AT!d is ignored in Pascal text@>
  2549. @.\AT!f is ignored in Pascal text@>
  2550.       ' is ignored in Pascal text'); goto continue;
  2551.     end;
  2552. new_module: goto done;
  2553. @ @<Copy a string...@>=
  2554. begin b:="'";
  2555. loop@+  begin app_repl(b);
  2556.   if b="@@" then
  2557.     if buffer[loc]="@@" then incr(loc) {store only one \.{@@}}
  2558.     else err_print('! You should double @@ signs in strings');
  2559. @.You should double \AT! signs@>
  2560.   if loc=limit then
  2561.     begin err_print('! String didn''t end');
  2562. @.String didn't end@>
  2563.     buffer[loc]:="'"; buffer[loc+1]:=0;
  2564.     end;
  2565.   b:=buffer[loc]; incr(loc);
  2566.   if b="'" then
  2567.     begin if buffer[loc]<>"'" then goto found
  2568.     else  begin incr(loc); app_repl("'");
  2569.       end;
  2570.     end;
  2571.   end;
  2572. found: end {now |a| holds the final |"'"| that will be stored}
  2573. @ @<Copy verbatim string...@>=
  2574. begin app_repl(verbatim);
  2575. buffer[limit+1]:="@@";
  2576. while buffer[loc]<>"@@" do
  2577.   begin app_repl(buffer[loc]);
  2578.   incr(loc);
  2579.   if loc<limit then
  2580.     if (buffer[loc]="@@") and (buffer[loc+1]="@@") then
  2581.       begin app_repl("@@");
  2582.       loc:=loc+2;
  2583.       end;
  2584.   end;
  2585. if loc>=limit then err_print('! Verbatim string didn''t end')
  2586. @.Verbatim string didn't end@>
  2587. else if buffer[loc+1]<>">" then
  2588.   err_print('! You should double @@ signs in verbatim strings');
  2589. @.You should double \AT! signs@>
  2590. loc:=loc+2;
  2591. end {another |verbatim| byte will be stored, since |a=verbatim|}
  2592. @ The following procedure is used to define a simple or parametric macro,
  2593. just after the `\.{==}' of its definition has been scanned.
  2594. @p procedure define_macro(@!t:eight_bits);
  2595. var p:name_pointer; {the identifier being defined}
  2596. begin p:=id_lookup(t); scan_repl(t);@/
  2597. equiv[p]:=cur_repl_text; text_link[cur_repl_text]:=0;
  2598. @* Scanning a module.
  2599. The |scan_module| procedure starts when `\.{@@\ }' or `\.{@@*}' has been
  2600. sensed in the input, and it proceeds until the end of that module.  It
  2601. uses |module_count| to keep track of the current module number; with luck,
  2602. \.{WEAVE} and \.{TANGLE} will both assign the same numbers to modules.
  2603. @<Globals...@>=
  2604. @!module_count:0..@'27777; {the current module number}
  2605. @ The top level of |scan_module| is trivial.
  2606. @p procedure scan_module;
  2607. label continue, done, exit;
  2608. var p:name_pointer; {module name for the current module}
  2609. begin incr(module_count);
  2610. @<Scan the \(definition part of the current module@>;
  2611. @<Scan the \PASCAL\ part of the current module@>;
  2612. exit: end;
  2613. @ @<Scan the \(definition part...@>=
  2614. next_control:=0;
  2615. loop@+  begin continue: while next_control<=format do
  2616.     begin next_control:=skip_ahead;
  2617.     if next_control=module_name then
  2618.       begin {we want to scan the module name too}
  2619.       loc:=loc-2; next_control:=get_next;
  2620.       end;
  2621.     end;
  2622.   if next_control<>definition then goto done;
  2623.   next_control:=get_next; {get identifier name}
  2624.   if next_control<>identifier then
  2625.     begin err_print('! Definition flushed, must start with ',
  2626. @.Definition flushed...@>
  2627.       'identifier of length > 1'); goto continue;
  2628.     end;
  2629.   next_control:=get_next; {get token after the identifier}
  2630.   if next_control="=" then
  2631.     begin scan_numeric(id_lookup(numeric)); goto continue;
  2632.     end
  2633.   else if next_control=equivalence_sign then
  2634.     begin define_macro(simple); goto continue;
  2635.     end
  2636.   else @<If the next text is `|(#)==|', call |define_macro|
  2637.     and |goto continue|@>;
  2638.   err_print('! Definition flushed since it starts badly');
  2639. @.Definition flushed...@>
  2640.   end;
  2641. done:
  2642. @ @<If the next text is `|(#)==|'...@>=
  2643. if next_control="(" then
  2644.   begin next_control:=get_next;
  2645.   if next_control="#" then
  2646.     begin next_control:=get_next;
  2647.     if next_control=")" then
  2648.       begin next_control:=get_next;
  2649.       if next_control="=" then
  2650.         begin err_print('! Use == for macros');
  2651. @.Use == for macros@>
  2652.         next_control:=equivalence_sign;
  2653.         end;
  2654.       if next_control=equivalence_sign then
  2655.         begin define_macro(parametric); goto continue;
  2656.         end;
  2657.       end;
  2658.     end;
  2659.   end;
  2660. @ @<Scan the \PASCAL...@>=
  2661. case next_control of
  2662. begin_Pascal:p:=0;
  2663. module_name: begin p:=cur_module;
  2664.   @<Check that |=| or |==| follows this module name, otherwise |return|@>;
  2665.   end;
  2666. othercases return
  2667. endcases;@/
  2668. @<Insert the module number into |tok_mem|@>;
  2669. scan_repl(module_name); {now |cur_repl_text| points to the replacement text}
  2670. @<Update the data structure so that the replacement text is accessible@>;
  2671. @ @<Check that |=|...@>=
  2672. repeat next_control:=get_next;
  2673. until next_control<>"+"; {allow optional `\.{+=}'}
  2674. if (next_control<>"=")and(next_control<>equivalence_sign) then
  2675.   begin err_print('! Pascal text flushed, = sign is missing');
  2676. @.Pascal text flushed...@>
  2677.   repeat next_control:=skip_ahead;
  2678.   until next_control=new_module;
  2679.   return;
  2680.   end
  2681. @ @<Insert the module number...@>=
  2682. store_two_bytes(@'150000+module_count); {|@'150000=@'320*@'400|}
  2683. @ @<Update the data...@>=
  2684. if p=0 then {unnamed module}
  2685.   begin text_link[last_unnamed]:=cur_repl_text; last_unnamed:=cur_repl_text;
  2686.   end
  2687. else if equiv[p]=0 then equiv[p]:=cur_repl_text {first module of this name}
  2688. else  begin p:=equiv[p];
  2689.   while text_link[p]<module_flag do p:=text_link[p]; {find end of list}
  2690.   text_link[p]:=cur_repl_text;
  2691.   end;
  2692. text_link[cur_repl_text]:=module_flag;
  2693.   {mark this replacement text as a nonmacro}
  2694. @* Debugging.
  2695. The \PASCAL\ debugger with which \.{TANGLE} was developed allows breakpoints
  2696. to be set, and variables can be read and changed, but procedures cannot be
  2697. executed. Therefore a `|debug_help|' procedure has been inserted in the main
  2698. loops of each phase of the program; when |ddt| and |dd| are set to appropriate
  2699. values, symbolic printouts of various tables will appear.
  2700. The idea is to set a breakpoint inside the |debug_help| routine, at the
  2701. place of `\ignorespaces|breakpoint:|\unskip' below.  Then when
  2702. |debug_help| is to be activated, set |trouble_shooting| equal to |true|.
  2703. The |debug_help| routine will prompt you for values of |ddt| and |dd|,
  2704. discontinuing this when |ddt<=0|; thus you type $2n+1$ integers, ending
  2705. with zero or a negative number. Then control either passes to the
  2706. breakpoint, allowing you to look at and/or change variables (if you typed
  2707. zero), or to exit the routine (if you typed a negative value).
  2708. Another global variable, |debug_cycle|, can be used to skip silently
  2709. past calls on |debug_help|. If you set |debug_cycle>1|, the program stops
  2710. only every |debug_cycle| times |debug_help| is called; however,
  2711. any error stop will set |debug_cycle| to zero.
  2712. @<Globals...@>=
  2713. @!debug@!trouble_shooting:boolean; {is |debug_help| wanted?}
  2714. @!ddt:integer; {operation code for the |debug_help| routine}
  2715. @!dd:integer; {operand in procedures performed by |debug_help|}
  2716. @!debug_cycle:integer; {threshold for |debug_help| stopping}
  2717. @!debug_skipped:integer; {we have skipped this many |debug_help| calls}
  2718. @!term_in:text_file; {the user's terminal as an input file}
  2719. gubed
  2720. @ The debugging routine needs to read from the user's terminal.
  2721. @^system dependencies@>
  2722. @<Set init...@>=
  2723. @!debug trouble_shooting:=true; debug_cycle:=1; debug_skipped:=0;@/
  2724. trouble_shooting:=false; debug_cycle:=99999; {use these when it almost works}
  2725. reset(term_in,'TTY:','/I'); {open |term_in| as the terminal, don't do a |get|}
  2726. gubed
  2727. @ @d breakpoint=888 {place where a breakpoint is desirable}
  2728. @^system dependencies@>
  2729. @p @!debug procedure debug_help; {routine to display various things}
  2730. label breakpoint,exit;
  2731. var k:integer; {index into various arrays}
  2732. begin incr(debug_skipped);
  2733. if debug_skipped<debug_cycle then return;
  2734. debug_skipped:=0;
  2735. loop@+  begin write(term_out,'#'); update_terminal; {prompt}
  2736.   read(term_in,ddt); {read a list of integers}
  2737.   if ddt<0 then return
  2738.   else if ddt=0 then
  2739.     begin goto breakpoint;@\ {go to every label at least once}
  2740.     breakpoint: ddt:=0;@\
  2741.     end
  2742.   else  begin read(term_in,dd);
  2743.     case ddt of
  2744.     1: print_id(dd);
  2745.     2: print_repl(dd);
  2746.     3: for k:=1 to dd do print(xchr[buffer[k]]);
  2747.     4: for k:=1 to dd do print(xchr[mod_text[k]]);
  2748.     5: for k:=1 to out_ptr do print(xchr[out_buf[k]]);
  2749.     6: for k:=1 to dd do print(xchr[out_contrib[k]]);
  2750.     othercases print('?')
  2751.     endcases;
  2752.     end;
  2753.   end;
  2754. exit:end;
  2755. gubed
  2756. @* The main program.
  2757. We have defined plenty of procedures, and it is time to put the last
  2758. pieces of the puzzle in place. Here is where \.{TANGLE} starts, and where
  2759. it ends.
  2760. @^system dependencies@>
  2761. @p begin initialize;
  2762. @<Initialize the input system@>;
  2763. print_ln(banner); {print a ``banner line''}
  2764. @<Phase I: Read all the user's text and compress it into |tok_mem|@>;
  2765. stat for zo:=0 to zz-1 do max_tok_ptr[zo]:=tok_ptr[zo];@+tats@;@/
  2766. @<Phase II:...@>;
  2767. end_of_TANGLE:
  2768. if string_ptr>256 then @<Finish off the string pool file@>;
  2769. stat @<Print statistics about memory usage@>;@+tats@;@/
  2770. @t\4\4@>{here files should be closed if the operating system requires it}
  2771. @<Print the job |history|@>;
  2772. @ @<Phase I:...@>=
  2773. phase_one:=true;
  2774. module_count:=0;
  2775. repeat next_control:=skip_ahead;
  2776. until next_control=new_module;
  2777. while not input_has_ended do scan_module;
  2778. @<Check that all changes have been read@>;
  2779. phase_one:=false;
  2780. @ @<Finish off the string pool file@>=
  2781. begin print_nl(string_ptr-256:1, ' strings written to string pool file.');
  2782. write(pool,'*');
  2783. for string_ptr:=1 to 9 do
  2784.   begin out_buf[string_ptr]:=pool_check_sum mod 10;
  2785.   pool_check_sum:=pool_check_sum div 10;
  2786.   end;
  2787. for string_ptr:=9 downto 1 do write(pool,xchr["0"+out_buf[string_ptr]]);
  2788. write_ln(pool);
  2789. @ @<Glob...@>=
  2790. stat @!wo:0..ww-1; {segment of memory for which statistics are being printed}
  2791. @ @<Print statistics about memory usage@>=
  2792. print_nl('Memory usage statistics:');
  2793. print_nl(name_ptr:1, ' names, ', text_ptr:1, ' replacement texts;');
  2794. print_nl(byte_ptr[0]:1);
  2795. for wo:=1 to ww-1 do print('+',byte_ptr[wo]:1);
  2796. print(' bytes, ', max_tok_ptr[0]:1);
  2797. for zo:=1 to zz-1 do print('+',max_tok_ptr[zo]:1);
  2798. print(' tokens.');
  2799. @ Some implementations may wish to pass the |history| value to the
  2800. operating system so that it can be used to govern whether or not other
  2801. programs are started. Here we simply report the history to the user.
  2802. @^system dependencies@>
  2803. @<Print the job |history|@>=
  2804. case history of
  2805. spotless: print_nl('(No errors were found.)');
  2806. harmless_message: print_nl('(Did you see the warning message above?)');
  2807. error_message: print_nl('(Pardon me, but I think I spotted something wrong.)');
  2808. fatal_message: print_nl('(That was a fatal error, my friend.)');
  2809. end {there are no other cases}
  2810. @* System-dependent changes.
  2811. This module should be replaced, if necessary, by changes to the program
  2812. that are necessary to make \.{TANGLE} work at a particular installation.
  2813. It is usually best to design your change file so that all changes to
  2814. previous modules preserve the module numbering; then everybody's version
  2815. will be consistent with the printed program. More extensive changes,
  2816. which introduce new modules, can be inserted here; then only the index
  2817. itself will get a new module number.
  2818. @^system dependencies@>
  2819. @* Index.
  2820. Here is a cross-reference table for the \.{TANGLE} processor.
  2821. All modules in which an identifier is
  2822. used are listed with that identifier, except that reserved words are
  2823. indexed only when they appear in format definitions, and the appearances
  2824. of identifiers in module names are not indexed. Underlined entries
  2825. correspond to where the identifier was declared. Error messages and
  2826. a few other things like ``ASCII code'' are indexed here too.
  2827.